Android开发之Notification手机状态栏通知用法实例分析
程序员文章站
2023-02-15 19:12:55
本文实例讲述了android开发之notification手机状态栏通知用法。分享给大家供大家参考,具体如下:
简介:
通知是显示在手机状态栏的通知(ps:就是手机上方...
本文实例讲述了android开发之notification手机状态栏通知用法。分享给大家供大家参考,具体如下:
简介:
通知是显示在手机状态栏的通知(ps:就是手机上方,显示时间啥的那一栏)
用法:
notification添加了builder()类,其包含如下方法:
1. setdefaults() 通知led灯、音乐、震动等
2. setautochange() 设置点击通知后,通知自动从状态栏删除
3. setcontenttitle() 通知标题
4. setcontenttext() 通知内容
5. setsmallcon() 为通知设置图标
6. setlargelcon() 为通知设置大图标
7. settick() 设置通知状态栏的提示文本
8. setcontentintent()点击通知后要启动的相应组件
运行效果:
实现方法:
1.首先建立一个活动用来执行:
public class mainactivity extends activity { static final int notification_id = 0x123; notificationmanager notificationmanager; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); //获取系统的notification对象 notificationmanager = (notificationmanager) getsystemservice(notification_service); } //为发送通知的按钮点击事件定义事件处理方法 @requiresapi(api = build.version_codes.jelly_bean) public void send(view source){ //创建一个其他activity的intent intent intent = new intent(mainactivity.this,textactivity.class); pendingintent pendingintent = pendingintent.getactivity(mainactivity.this,0,intent,0); notification notification = new notification.builder(this) //设置打开通知 通知自动消失 .setautocancel(true) //设置显示状态栏的通知提示信息 .setticker("注目提醒!") //设置通知图标 .setsmallicon(r.drawable.seek02) //设置通知内容标题 .setcontenttitle("该应用发生 爆炸大 大 大 新闻!!") //设置通知内容 .setcontenttext("冒险没有 你手机自嗨罢了~") //设置使用默认的声音 led灯 .setdefaults(notification.default_sound|notification.default_lights) //设置通知自定义声音 // .setsound() .setwhen(system.currenttimemillis()) //设置他只要启动的程序intent .setcontentintent(pendingintent) .build(); notificationmanager.notify(notification_id,notification); } public void del(view view){ //取消通知 notificationmanager.cancel(notification_id); } }
2.然后建立一个要打开的活动(随意建就行)(布局文件任意我这里就不写了)
public class textactivity extends appcompatactivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_t_exta_ctivity); } }
最后记得添加权限(mainfest)
<!--消息通知使用到闪光灯和声音权限--> <uses-permission android:name="android.permission.flashlight"/> <uses-permission android:name="android.permission.vibrate"/>
ps:关于android权限控制可参考~
android manifest功能与权限描述大全: http://tools.jb51.net/table/androidmanifest
更多关于android相关内容感兴趣的读者可查看本站专题:《android开发入门与进阶教程》、《android调试技巧与常见问题解决方法汇总》、《android基本组件用法总结》、《android视图view技巧总结》、《android布局layout技巧总结》及《android控件用法总结》
希望本文所述对大家android程序设计有所帮助。