標籤:
原文地址:http://android.xsoftlab.net/training/notify-user/managing.html#Removing
當需要在不同時段發布同一事件類型的通知時,應當避免建立新的通知。相反的,應當考慮更新原有的通知,比如更改通知的某些值或者添加一些資訊給通知。
下面的部分描述了如何更新通知以及如何移除通知。
修改通知
為了設定通知是可以更新的,需要在發布通知時由NotificationManager.notify(ID, notification)方法指定該通知的ID。為了更新這條通知,需要更新或者建立一個NotificationCompat.Builder對象,並由這個對象構建一個Notification對象,然後將這個通知對象以相同的ID發布出去。
下面的程式碼片段示範了在事件發生時,一條通知將會被用來更新該事件的數目:
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);// Sets an ID for the notification, so it can be updatedint 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());...
移除通知
在以下事件發生時,通知將會從通知欄中移除:
- 使用者移除了該通知或者使用了”Clear All”功能(如果通知是可移除的話)。
- 使用者點擊了通知,這條通知在建立時使用了setAutoCancel(false)方法(false是預設屬性)。
- 通過調用cancel()方法並指定該通知的ID。這個方法還可以移除進行中的通知。
- 通過調用cancelAll()方法,將已經發布的所有通知移除。
Android官方開發文檔Training系列課程中文版:通知使用者之更新或移除通知