In my app, I place my Service in the foreground to prevent it from being killed by using:
startForeground(NOTIFY_ID, notification);
This also displays the notification to the user (which is great). The problem is that later I need to update the notification. So I use the code:
notification.setLatestEventInfo(getApplicationContext(), someString, someOtherString, contentIntent);
mNotificationManager.notify(NOTIFY_ID, notification);
The question then is: will doing this knock the Service out of it's special foreground status?
In this answer, CommonsWare indicates that this behavior is possible, but he's not sure. So does anyone know the actual answer?
Note: I am aware that a simple way to get out of this question is to repeatedly call startForeground()
every time I want to update the notification. I'm looking to know whether this alternative will also work.
When you want to update a Notification set by startForeground(), simply build a new notication and then use NotificationManager to notify it.
The key point is to use the same notification id.
Updating the Notification will NOT remove the Service from the foreground status (this can be done only by calling stopForground );
Example:
The RandomMusicPlayer (archived) app at the Android developer site uses NotificationManager to update the notification of a foreground service, so chances are pretty good that it retains the foreground status.
(See setUpAsForeground() and updateNotification() in the MusicService.java class.)
From what I understand, if you cancel the notification the service will cease being a foreground service, so keep that in mind; if you cancel the notification, you'll need to call startForeground() again to restore the service's foreground status.
To clarify what has been said here:
This part of the answer suggest it is possible to remove an ongoing
Notification
set by aService
by usingNotificationManager.cancel()
on the persistentNotification
. This is not true. It's impossible to remove a ongoing notification set bystartForeground()
by usingNotificationManager.cancel()
.The only way to remove it, is to call
stopForeground(true)
, so the ongoing Notification is removed, which ofcourse also makes theService
stop being in the foreground. So it's actually the other way around; theService
doesn't stop being in the foreground because theNotification
is cancelled, theNotification
can only be cancelled by stopping theService
being in the foreground.Naturally one could call
startForeground()
after this right away, to restore the state with a newNotification
. One reason you would want to do this if a ticker text has to be shown again, because it will only run the first time theNotification
is displayed.This behaviour is not documented, and I wasted 4 hours trying to figure out why I couldn't remove the
Notification
. More on the issue here: NotificationManager.cancel() doesn't work for me