Search code examples
androidandroid-notificationsandroid-lifecycle

Cancel notification after application is closed from background


I have an activity that shows a notification on notification bar. If the user goes to the background pressing the home button I keep the notification (that's what I need), but when the user closes the application I need to cancel the notification and that's my problem.

  • I tried to cancel notification on onDestroy but it´s not fired.
  • I tried to set setOngoing true for the notification.

How could I deal with this? Every time the user goes background and then close the app I need to remove the notification from the notification bar, but if the user keep the application in background I need the notification.


Solution

  • You have your notification an ID when your created it, right?

    Then all you have to do is use that ID to cancel it.
    For example:

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.cancel(4);
    

    on destroy is fired when they back out of your app or if you call finish() on your activity.