Notification的例子,请参考附件。
1. 创建Notification builder
2. 定义notification action
3. 设置notification点击的行为
4. 启动notification
5. 取消notification
1. 创建Notification builder
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon) // 一个图标
.setContentTitle("My notification") // 标题
.setContentText("Hello World!"); // 具体内容
2. 定义notification action
Intent resultIntent = new Intent(this, ResultActivity.class); // 点击后跳转的activity
...
// 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
);
3. 设置notification点击的行为
PendingIntent resultPendingIntent;
...
mBuilder.setContentIntent(resultPendingIntent);
4. 启动notification
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());
5. 取消notification
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(NOTIFICATION_ID);