Android 更新Notification

2018-08-02 18:09 更新

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

當(dāng)你需要對同一事件發(fā)布多次Notification時(shí),你應(yīng)該避免每次都生成一個(gè)全新的Notification。相反,你應(yīng)該考慮去更新先前的Notification,或者改變它的值,或者增加一些值,或者兩者同時(shí)進(jìn)行。

下面的章節(jié)描述了如何更新Notifications,以及如何移除它們。

改變一個(gè)Notification

想要設(shè)置一個(gè)可以被更新的Notification,需要在發(fā)布它的時(shí)候調(diào)用NotificationManager.notify(ID, notification))方法為它指定一個(gè)notification ID。更新一個(gè)已經(jīng)發(fā)布的Notification,需要更新或者創(chuàng)建一個(gè)NotificationCompat.Builder對象,并從這個(gè)對象創(chuàng)建一個(gè)Notification對象,然后用與先前一樣的ID去發(fā)布這個(gè)Notification。

下面的代碼片段演示了更新一個(gè)notification來反映事件發(fā)生的次數(shù),它把notification堆積起來,顯示一個(gè)總數(shù)。


mNotificationManager =
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
    .setContentTitle("New Message")
    .setContentText("You've received new messages.")
    .setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
    mNotifyBuilder.setContentText(currentText)
        .setNumber(++numMessages);
    // Because the ID remains unchanged, the existing notification is
    // updated.
    mNotificationManager.notify(
            notifyID,
            mNotifyBuilder.build());
...

移除Notification

Notifications 將持續(xù)可見,除非下面任何一種情況發(fā)生。

* 用戶清除Notification單獨(dú)地或者使用“清除所有”(如果Notification能被清除)。
* 你在創(chuàng)建notification時(shí)調(diào)用了 setAutoCancel(developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#setAutoCancel(boolean))方法,以及用戶點(diǎn)擊了這個(gè)notification,
* 你為一個(gè)指定的 notification ID調(diào)用了[cancel()](developer.android.com/reference/android/app/NotificationManager.html#cancel(int))方法。這個(gè)方法也會刪除正在進(jìn)行的notifications。
* 你調(diào)用了[cancelAll()](developer.android.com/reference/android/app/NotificationManager.html#cancelAll())方法,它


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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號