編寫:fastcome1985 - 原文:http://developer.android.com/training/notify-user/build-notification.html
這節(jié)課向你說明如何創(chuàng)建與發(fā)布一個Notification。
創(chuàng)建Notification時,可以用NotificationCompat.Builder對象指定Notification的UI內(nèi)容與行為。一個Builder至少包含以下內(nèi)容:
例如:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
盡管在Notification中Actions是可選的,但是你應(yīng)該至少添加一種Action。一種Action可以讓用戶從Notification直接進入你應(yīng)用內(nèi)的Activity,在這個activity中他們可以查看引起Notification的事件或者做下一步的處理。在Notification中,action本身是由PendingIntent定義的,PendingIntent包含了一個啟動你應(yīng)用內(nèi)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
);
可以通過調(diào)用NotificationCompat.Builder中合適的方法,將上一步創(chuàng)建的PendingIntent與一個手勢產(chǎn)生關(guān)聯(lián)。比方說,當(dāng)點擊Notification抽屜里的Notification文本時,啟動一個activity,可以通過調(diào)用setContentIntent()方法把PendingIntent添加進去。
例如:
PendingIntent resultPendingIntent;
...
mBuilder.setContentIntent(resultPendingIntent);
為了發(fā)布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());