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.
To clarify what has been said here:
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.
This part of the answer suggest it is possible to remove an ongoing Notification
set by a Service
by using NotificationManager.cancel()
on the persistent Notification
.
This is not true.
It's impossible to remove a ongoing notification set by startForeground()
by using NotificationManager.cancel()
.
The only way to remove it, is to call stopForeground(true)
, so the ongoing Notification is removed, which ofcourse also makes the Service
stop being in the foreground. So it's actually the other way around; the Service
doesn't stop being in the foreground because the Notification
is cancelled, the Notification
can only be cancelled by stopping the Service
being in the foreground.
Naturally one could call startForeground()
after this right away, to restore the state with a new Notification
. 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 the Notification
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With