Noficication的那些事(一)
应用中经常会使用通知与用户进行交互,对于创建通知,官方建议使用NotificationCompat.Bulder或则它的子类,这样能够很好的适配不同版本的设备。
创建 Notification Builder
创建通知,最少需要设置通知的三个属性:
- 小图标 通过
setSmallIcon()
设置; - 标题 通过
setContentTitle()
设置; - 详细文字 通过
setContentText()
设置;
例如:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
定义通知的行为
一般的,我们会为通知设置点击行为,定义通知的行为需要用到PendingIntent
,
下面构造了一个PendingIntent
用来打开 ResultActivity
Intent resultIntent = new Intent(this, ResultActivity.class);
...
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
设置通知的行为
定义好了通知的行为,下面我们需要为Notification
关联PendingIntent
,代码如下:
PendingIntent resultPendingIntent;
...
mBuilder.setContentIntent(resultPendingIntent);
发布通知
调用
mBuilder.builder
得到指定的待发布的通知;在发布通知之前,首先需要获取
NotificationManager
的实例;使用
notify()
发布通知,在调用notify()
发布通知的时候,指定通知的id,以后可以通过这个id来更新通知的内容;例如:
NotificationCompat.Builder mBuilder; ... // Sets an ID for the notification int mNotificationId = 001; // Gets an instance of the NotificationManager service NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); // Builds the notification and issues it. mNotifyMgr.notify(mNotificationId, mBuilder.build());