The android docs state that for a service to be started, the onStartCommand
has to be implemented. When I made the service
, and start the service using ContextCompat.startForegroundService(...)
, then it's onStartCommand
method gets executed, and at this point even when I quit the app , the service doesn't stop (as expected).
But, later when I make updates to the notification by changing the text displayed, I use the notificationManager.notify()
method, and now when I quit the app, the service automatically stops. I wonder if we are suppose to force call onStartCommand on every notification update, somehow(like should we update the notification with ContextCompat.startForegroundService
? I've tested this from api level 19
to api level 27
and the behaviour is all the same. How can I maintain the property of the service as started
even after I update the notification?
I wonder if we are suppose to force call
onStartCommand
on every notification update,
No you are not forced to call onStartCommand
on every notification update
somehow(like should we update the notification with
ContextCompat.startForegroundService
? I've tested this from API level 19 to API level 27 and the behaviour is all the same. How can I maintain the property of the service as started even after I update the notification?
You should call ContextCompat.startForegroundService
only once for starting a ForegroundService
.
In order to update the ForegroundSerice
notification without being destroyed when you quit your app, you can use startForeground()
every time you want to update the foreground service notification.
A famous example on this to update a downloading service with the download progress to something like a ProgressBar
.
The important thing: you need to make sure you use the same notification ID while calling startForeground()
startForeground()
won't call onStartCommand
; If that could be possible, then I guess this would make an endless loop.
Whenever you want to stop the foreground service, and submit a normal notification (Download complete in download example), then you can submit a normal notification with notificationManager.notify()
, and this will allow the user to dismiss the notification by swiping it.
Issue: When submitting a normal notification after the foreground service is stopped; the normal notification is dismissed as well.
Cause: This is because you use the same notification ID that you've used with the foreground service, so stopping the foreground service will also dismiss the normal notification.
Solution: make sure to have different notification IDs of the foreground service notification and the normal notification that is dispatched upon stopping the foreground service.
Also make sure to call below to stop the foreground service:
stopForeground(true);
stopSelf();