How to Clear Notifications in Your Android App - dummies

How to Clear Notifications in Your Android App

By Michael Burton

Notifications can’t stay on your users’ devices forever; they have to be cleared someway. Users constitute an unpredictable group — whether they’re first-time users or advanced power users, they can be located anywhere in the world and use their devices in their own, special ways.

At some point, a user may see a notification and decide to open the app using the app launcher instead. If this happens while a notification is active, the notification persists.

Even if the user looks at the task at hand, the notification still persists on the status bar. Your application should be able to simply recognize the state of the application and take the appropriate measures to cancel any existing notifications for the task. However, if the user opens your app and reviews a different task that has no active notification, your app shouldn’t clear the notification.

Clear only the notification that the user is reviewing. The NotificationManager makes it simple to cancel an existing notification by using the cancel() method. This method accepts one parameter — the ID of the notification. You may recall using the ID of the task as the ID of the note. The ID of the task is unique to the Tasks application.

By doing this, you can easily open a task and cancel any existing notification by calling the cancel() method with the ID of the task.

At some point, you might also need to clear all previously shown notifications. To do this, simply call the cancelAll() method on the NotificationManager.