W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
編寫:fastcome1985 - 原文:http://developer.android.com/training/notify-user/build-notification.html
這節(jié)課向你說明如何創(chuàng)建與發(fā)布一個Notification。
這節(jié)課的例子是基于NotificationCompat.Builder類的,NotificationCompat.Builder在Support Library中。為了給許多各種不同的平臺提供最好的notification支持,你應該使用NotificationCompat以及它的子類,特別是NotificationCompat.Builder。
創(chuàng)建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。
如何構建一個PendingIntent取決于你要啟動的activity的類型。當從Notification中啟動一個activity時,你必須保存用戶的導航體驗。在下面的代碼片段中,點擊Notification啟動一個新的activity,這個activity有效地擴展了Notification的行為。在這種情形下,就沒必要人為地去創(chuàng)建一個返回棧(更多關于這方面的信息,請查看 Preserving Navigation when Starting an Activity)
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中合適的方法,將上一步創(chuàng)建的PendingIntent與一個手勢產(chǎn)生關聯(lián)。比方說,當點擊Notification抽屜里的Notification文本時,啟動一個activity,可以通過調用setContentIntent())方法把PendingIntent添加進去。
例如:
PendingIntent resultPendingIntent;
...
mBuilder.setContentIntent(resultPendingIntent);
為了發(fā)布notification:
* 獲取一個[NotificationManager](http://www.baidu.com/baidu?wd=NotificationManager.&tn=monline_4_dg)實例
* 使用[notify()](developer.android.com/reference/java/lang/Object.html#notify())方法發(fā)布Notification。當你調用[notify()](developer.android.com/reference/java/lang/Object.html#notify())方法時,指定一個notification ID。你可以在以后使用這個ID來更新你的notification。這在[Managing Notifications](developer.android.com/intl/zh-cn/training/notify-user/managing.html)中有更詳細的描述。
* 調用[build()](developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#build())方法,會返回一個包含你的特征的[Notification](developer.android.com/reference/android/app/Notification.html)對象。
舉個例子:
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());
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: