做为刚入门Android的小白,最近在按照郭大神的《第一行代码》在练习,在用到Notification时遇到了一些问题,网上资料比较零散,我这里作了一个总结分析给各位,如有错误,恳请指正~html
Notification是一种具备全局效果的通知,程序通常经过NotificationManager服务来发送Notification。java
Notification支持文字内容显示、震动、三色灯、铃声等多种提示形式,在默认状况下,Notification仅显示消息标题、消息内容、送达时间这3项内容。android
如下就是通知的基本布局:app
不一样API level的区别主要是Notification的构造方法、获得实例的方法,这里顺便总结一下Notification的用法,按照步骤分别给出不一样API level下的作法:布局
一、获取Notification管理器ui
NotificationManager noteManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
获取管理器的方式都同样,没有改变。this
二、新建一个Notification,设置状态栏显示样式spa
这里只列举了最简单的样式设置,具体的你们能够参考API文档。code
// API Level < 11 (Android 3.0) Notification notification = new Notification( R.mipmap.ic_launcher, "This is ticker text", System.currentTimeMillis());
API<11时,能够直接用Notification的构造方法新建一个Notification,十分方便。orm
ps:我用的IDE是AndroidStudio,因此icon的id是R.mipmap.***。
// API Level >= 11 (Android 3.0) && API Level < 16 (Android 4.1) Notification.Builder builder = new Notification.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setTicker("This is ticker text") .setWhen(System.currentTimeMillis()); Notification note = builder.getNotification(); // 调用getNotification()来生成Notification
API>11后,就要用Notification.Builder()来代替了,官方API是这样说的:
Notification(int icon, CharSequence tickerText, long when)
Notification.Builder
instead.
NotificationCompat.Builder
, available in the
Android Support library.
//API Level >= 4 (Android 1.6) && API Level < 16 (Android 4.1) NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setTicker("This is ticker text") .setWhen(System.currentTimeMillis()); Notification note =builder.getNotification(); //调用builder.getNotification()来生成Notification
所以推荐用NotificationCompat.Builder这种方式。
注意到我在注释里写的 "&& API Level < 16 (Android 4.1)" 了吗?这是由于在Google官方API文档上是这么说的:
public Notification getNotification () Added in API level 11
This method was deprecated in API level 16.
Use build()
instead
所以,当API>=16即Android4.1以后,就要用build()来代替了,使用方法同样,在此就不赘述了。
三、设置Notification的触发事件
点击Notification后,通常都是触发一个新的Activity:
Intent intent = new Intent(this, AnotherActivity.class); PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
这里不一样API版本都同样。
四、设置Notification在通知栏里的样式
// API Level < 11 (Android 3.0) note.setLatestEventInfo(this, "This is content title", "This is content text", pi);
API<11时,调用的是Notification类的setLatestEventInfo方法。
// API Level >= 11 (Android 3.0) builder.setContentIntent(pi) .setContentTitle("This is content title") .setContentText("This is content text");
而当API>=11时,设置通知栏中的样式是调用Builder的setContentIntent方法,设置好以后在调用build()方法生成Notification实例。
相似的,NotificationCompat.Builder也是调用一样的方法,这里就不赘述了。
五、发布该Notification
第一个参数为该notification的ID
noteManager.notify(1, note);
总结一下:
低版本(API低于十一、16)中的部分方法已经被弃用:
(1)Notification.Builder(this).getNotification()
(2)mNotification.setLatestEventInfo(this, "title", "content", null);
建议开发过程当中尽可能使用NotificationCompat.Builder(this)的构建方法去建立一个通知类。