Android Service startForeground and stopForeground tip

I had a use case for an application that required a long running Service (I know they are always frowned upon). The service seemed to be getting killed during the night and stuck in the “restarting” stage (Settings > Apps > Running). The Service would never restart at some point after being killed. So to raise its priority I used startForeground().

The Service already uses notifications so it wasn’t a big deal to have one required by startForeground(). The problem I ran into was when using stopForeground() to remove the the Service from the foreground followed by a stopService() call. This seemed to kill my Notification which I wanted to remain displaying the results of the service.

By default stopForeground() removes all Notifications when the service is stopped while still in the foreground:

“if you stop the service while it’s still running in the foreground, then the notification is also removed.”

What I concluded was that the order of the stopForeground() service is important. You have to create a notification after you use stopForeground() and before you use stopSelf() in order to preserve your last Notification. Just using stopForeground(false) does not keep the notification around if the service is then stopped (stopSelf()).

This might be must a niche use case (or corner case) but it’s one I needed and thought I might share.