天天看点

android: Android Notification

notification即通知,用于在通知栏显示提示信息。

在较新的版本中(api level  > 11),notification类中的一些方法被android声明deprecated(弃用),其实基本上相当于全部弃用了,因为这个类本身方法就少得可怜。

android官方声明弃用,一定有它的理由,虽然我也不知道是什么。奈何本人轻度强迫症患者,人家都建议你不要用了,那就不要老是恪守着n年前的东西了。

就像是以前,一说到标签页,大家基本上都会想到tabhost配合activitygroup,但android后来提倡fragment。

废话说多了,还是小结一下使用方法。下面按照创建一个通知的步骤一步一步来,同时给出新旧实现方法。

1、获取notification管理器

notificationmanager notemng = (notificationmanager)getsystemservice(notification_service);

2、新建一个notification,设置状态栏显示样式

private notification note;

//api 11以下

note = new notification(r.drawable.ico_launcher "显示于屏幕顶端状态栏的文本", system.currenttimemillis());

//api 11及以上

notification.builder builder = new notification.builder(nowcontext).setticker("显示于屏幕顶端状态栏的文本")

.setsmallicon(r.drawable.ic_laucher);

api 11以上版本中,状态栏显示的样式跟下拉通知栏中显示的样式,可以一起设置,就是通过notification.builder类来实现,这里的builder只调用了两个方法来设置状态栏显示样式。

3、设置notification标志位(非必要步骤)

//flag_ongoing_event表明有程序在运行,该notification不可由用户清除

note.flags = notification.flag_ongoing_event;

4、设置点击notification后的触发事件

//通过intent,使得点击notification之后会启动新的activity

intent i = new intent(nowcontext, anotheractivity.class);

//该标志位表示如果intent要启动的activity在栈顶,则无须创建新的实例

i.setflags(intent.flag_activity_single_top);

pendingintent = pendingintent.getactivity(nowcontext, 100, i, pendingintent.flag_update_current);

5、设置notification在通知栏里的样式

(1)系统默认样式

//api 11以下:

note.setlatesteventinfo(nowcontext, "take me to your heart", "micheal learn to rock", pendingintent);

//api 16及以上,build()方法要求api 16及以上

//一会api 11以上,一会api16以上,我也很想知道android的api是怎么设计的

note = builder.setcontentintent(pendingintent).setcontenttitle("title").setcontenttext("text").build();

(2)自定义样式:

自定义样式,就是让notification在通知栏显示成自定义的xml布局

应当注意的是,notification的自定义样式,只支持以下可视组件:

framelayout, linearlayout, relativelayout

textview, button, analogclock, imageview, imagebutton, chronometer, progressbar

remoteview view = new remoteview(nowactivity.getpackagename(), r.layout.note_layout);

note.contentview = view;

note.contentintent = pendingintent;

//api 16及以上,又是build()方法导致的,汗。。

note = builder.setcontent(view).setcontentintent(pendingintent).build();

这个步骤里有一个很值得注意的地方:pendingintent被设置为note的contentintent的值,就意味着点击了这个通知才会触发该intent。

那么如果只是想让自定义布局里的某个按钮触发呢?比如说,弄了一个音乐播放器,service负责播放音乐,notification显示当前播放进度和一些简单的暂停按钮、上一首、下一首按钮,让用户不用再打开界面就可以通过notification上的按钮操纵音乐播放。

假设说想让自定义布局里的一个id为r.id.button1的按钮来触发这个intent,可以如下操作:

view.setonclickpendingintent(r.id.button1, pendingintent);//在上面创建remoteview实例后加上这句

然后注意,pendingintent已经绑定到按钮上了,上面notificatiion实例中,设置contentintent的语句要去掉。

6、发布该通知,第一个参数为该notification的id

notemng.notify(10, note);

ps:这个是我自己敲的一个txt文件,在我电脑里,可能一些变量名什么的会敲错。

但是大概步骤跟方法相信已经说清楚了。