Stop Android service in activity onDestroy()

Viewed 257

I try to manage a Android foreground service to upload data to server. One of the requirements is to kill the service when the user close the app (e.g. swiping up to close app). The service is started in the onStart lifecycle with startService of Activity A and killed in onDestroy by stopService in the same activity. When I close the app and go to:

Developer options > Running Services > Show cached processes

I can see my app is still there and occupying system memory. The interesting thing is if I stopService in onStop lifecycle and when the app is closed, my app is no longer in the cached processes list. My question is is there a way to prevent the app from being caching in the system by still stopService in onDestroy lifecycle.

1 Answers

According to official android documentation: Link of foreground service docs

To remove the service from the foreground, call stopForeground(). This method takes a boolean, which indicates whether to remove the status bar notification as well. Note that the service continues to run.

If you stop the service while it's running in the foreground, its notification is removed.

For understanding of cached processes.

Check this Link

Related