编写:fastcome1985 - 原文:http://developer.android.com/training/notify-user/build-notification.html
这节课向你说明如何创建与发布一个Notification。
创建Notification时,可以用NotificationCompat.Builder对象指定Notification的UI内容与行为。一个Builder至少包含以下内容:
例如:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
尽管在Notification中Actions是可选的,但是你应该至少添加一种Action。一种Action可以让用户从Notification直接进入你应用内的Activity,在这个activity中他们可以查看引起Notification的事件或者做下一步的处理。在Notification中,action本身是由PendingIntent定义的,PendingIntent包含了一个启动你应用内Activity的Intent。
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
);
可以通过调用NotificationCompat.Builder中合适的方法,将上一步创建的PendingIntent与一个手势产生关联。比方说,当点击Notification抽屉里的Notification文本时,启动一个activity,可以通过调用setContentIntent()方法把PendingIntent添加进去。
例如:
PendingIntent resultPendingIntent;
...
mBuilder.setContentIntent(resultPendingIntent);
为了发布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());