Android 建立一個(gè)Notification

2018-08-02 18:09 更新

編寫:fastcome1985 - 原文:http://developer.android.com/training/notify-user/build-notification.html

創(chuàng)建Notification Buider

例如:


NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!");

定義Notification的Action(行為)

  • 盡管在Notification中Actions是可選的,但是你應(yīng)該至少添加一種Action。一種Action可以讓用戶從Notification直接進(jìn)入你應(yīng)用內(nèi)的Activity,在這個(gè)activity中他們可以查看引起Notification的事件或者做下一步的處理。在Notification中,action本身是由PendingIntent定義的,PendingIntent包含了一個(gè)啟動(dòng)你應(yīng)用內(nèi)ActivityIntent。

  • 如何構(gòu)建一個(gè)PendingIntent取決于你要啟動(dòng)的activity的類型。當(dāng)從Notification中啟動(dòng)一個(gè)activity時(shí),你必須保存用戶的導(dǎo)航體驗(yàn)。在下面的代碼片段中,點(diǎn)擊Notification啟動(dòng)一個(gè)新的activity,這個(gè)activity有效地?cái)U(kuò)展了Notification的行為。在這種情形下,就沒必要人為地去創(chuàng)建一個(gè)返回棧(更多關(guān)于這方面的信息,請(qǐ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
);

設(shè)置Notification的點(diǎn)擊行為

可以通過調(diào)用NotificationCompat.Builder中合適的方法,將上一步創(chuàng)建的PendingIntent與一個(gè)手勢(shì)產(chǎn)生關(guān)聯(lián)。比方說,當(dāng)點(diǎn)擊Notification抽屜里的Notification文本時(shí),啟動(dòng)一個(gè)activity,可以通過調(diào)用setContentIntent())方法把PendingIntent添加進(jìn)去。

例如:


PendingIntent resultPendingIntent;
...
mBuilder.setContentIntent(resultPendingIntent);

發(fā)布Notification

為了發(fā)布notification:

* 獲取一個(gè)[NotificationManager](http://www.baidu.com/baidu?wd=NotificationManager.&tn=monline_4_dg)實(shí)例
* 使用[notify()](developer.android.com/reference/java/lang/Object.html#notify())方法發(fā)布Notification。當(dāng)你調(diào)用[notify()](developer.android.com/reference/java/lang/Object.html#notify())方法時(shí),指定一個(gè)notification ID。你可以在以后使用這個(gè)ID來更新你的notification。這在[Managing Notifications](developer.android.com/intl/zh-cn/training/notify-user/managing.html)中有更詳細(xì)的描述。
* 調(diào)用[build()](developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#build())方法,會(huì)返回一個(gè)包含你的特征的[Notification](developer.android.com/reference/android/app/Notification.html)對(duì)象。

舉個(gè)例子:


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());


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)