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

3

7

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.

Plunk answered 8/7, 2012 at 22:44 Comment(2)
You're trying to remove a notification which was started from a different application?Cwmbran
no, it's the same applicationPlunk
L
14

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.

Lilialiliaceous answered 8/7, 2012 at 23:19 Comment(1)
they should really put this in the documentation or have it throw an error when this is attempted...Plunk
D
7

You can always remove notification from a foreground service by callng stopForeground(boolean removeNotification). Then a service exits his foregroundState and once again can be killed by the system when the memory is needed.

Dendroid answered 21/2, 2014 at 5:48 Comment(0)
Z
0

You could update the notification by passing in an empty Builder.

if(showNotification){
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setVisibility(Notification.VISIBILITY_SECRET)
            .setSmallIcon(R.mipmap.ic_spotify_white_24dp)
            .setTicker("Playing Now")
            .setContentTitle("Spotify")
            .setContentText("Preview");
    return mBuilder;
}else{
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
    return mBuilder;
}
Zondra answered 17/8, 2015 at 17:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.