Updating Notifications

This lesson teaches you to

  1. Modify a Notification
  2. Remove Notifications

You should also read

When you need to issue a notification multiple times for the same type of event, you should avoid making a completely new notification. Instead, you should consider updating a previous notification, either by changing some of its values or by adding to it, or both.

The following section describes how to update notifications and also how to remove them.

Modify a Notification

To set up a notification so it can be updated, issue it with a notification ID by calling NotificationManager.notify(ID, notification). To update this notification once you've issued it, update or create a NotificationCompat.Builder object, build a Notification object from it, and issue the Notification with the same ID you used previously.

The following snippet demonstrates a notification that is updated to reflect the number of events that have occurred. It stacks the notification, showing a summary:

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

Remove Notifications

Notifications remain visible until one of the following happens:

  • The user dismisses the notification either individually or by using "Clear All" (if the notification can be cleared).
  • The user touches the notification, and you called setAutoCancel() when you created the notification.
  • You call cancel() for a specific notification ID. This method also deletes ongoing notifications.
  • You call cancelAll(), which removes all of the notifications you previously issued.