本文实例讲述了android开发之notification手机状态栏通知用法。分享给大家供大家参考,具体如下:
简介:
通知是显示在手机状态栏的通知(ps:就是手机上方,显示时间啥的那一栏)
用法:
notification添加了builder()类,其包含如下方法:
1. setdefaults() 通知led灯、音乐、震动等
2. setautochange() 设置点击通知后,通知自动从状态栏删除
3. setcontenttitle() 通知标题
4. setcontenttext() 通知内容
5. setsmallcon() 为通知设置图标
6. setlargelcon() 为通知设置大图标
7. settick() 设置通知状态栏的提示文本
8. setcontentintent()点击通知后要启动的相应组件
运行效果:
实现方法:
1.首先建立一个活动用来执行:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
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.然后建立一个要打开的活动(随意建就行)(布局文件任意我这里就不写了)
1
2
3
4
5
6
7
|
public class textactivity extends appcompatactivity { @override protected void oncreate(bundle savedinstancestate) { super .oncreate(savedinstancestate); setcontentview(r.layout.activity_t_exta_ctivity); } } |
最后记得添加权限(mainfest)
1
2
3
|
<!--消息通知使用到闪光灯和声音权限--> <uses-permission android:name= "android.permission.flashlight" /> <uses-permission android:name= "android.permission.vibrate" /> |
ps:关于android权限控制可参考~
android manifest功能与权限描述大全
希望本文所述对大家android程序设计有所帮助。
原文链接:https://blog.csdn.net/qq_43377749/article/details/85018762