Search code examples
androidandroid-serviceforegroundandroid-notificationsnotificationmanager

NotificationManager.cancel() doesn't work: Notification isn't removed


I've been trying to remove a persistent Notification set by a Service using:

startForeground(1337, notification);

The code I'm using to cancel it:

NotificationManager nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.cancel(1337);  // cancel existing service notification, doesn't take effect
nManager.cancelAll(); //surpluous, but also doesn't take effect

To clarify why I am doing this: the Service starts with a default persistent Notification. When my app runs, it needs to replace this Notification with another. Using notify() on the existing Notification works perfectly, however, I need it to show the ticker text for the new Notification as well. This is why I decided to remove the existing Notification (using the code above), create a new one, and then I call startForeground() again and pass the new Notification to it, so my Service persists.


Solution

  • The problem is that you're issuing the Notification in an indirect way by using startForeground(). You can't just cancel that Notification for the same reason the system insists on you providing a Notification when starting a foreground Service. As long as your foreground Service is running, that Notification will be there.

    In most cases, Services really shouldn't be in the foreground. If you can use a normal priority for your Service, then you can start and stop your Notification normally.

    If you're actually doing something that truly does require a foreground Service, and if you really want to show the user a ticker text, I believe your only option is to issue another Notification.