Search code examples
androidserviceondestroy

Android - destroying service on calling stopService


I have a background service that I start and stop using startService() and stopService() when the respective buttons are pressed on the UI ("connect" and "disconnect" respectively).

I perform a lot of clean up operations when the service is stopped, and I put those in the service's onDestroy() assuming that would be called whenever stopService() is called. However, I observed that onDestroy() is not called immediately when stopService() is called. It might be called in some time, or after a very long time.

What can I do to ensure those clean-up operations are performed as soon as stopService() is called (which is triggered whenever someone clicks the "disconnect" button) ? Do I have to go for the bindService() approach, or is there some other way ?

Note: The service is running in a process of its own, within the same application.


Solution

  • From the docs:

    Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon as possible.

    However, if your service handles multiple requests to onStartCommand() concurrently, then you shouldn't stop the service when you're done processing a start request, because you might have since received a new start request (stopping at the end of the first request would terminate the second one). To avoid this problem, you can use stopSelf(int) to ensure that your request to stop the service is always based on the most recent start request. That is, when you call stopSelf(int), you pass the ID of the start request (the startId delivered to onStartCommand()) to which your stop request corresponds. Then if the service received a new start request before you were able to call stopSelf(int), then the ID will not match and the service will not stop.

    Since stopSelf() or stopService() kill the service as soon as possible there might be other factors that are keeping it alive (since you say it sometimes takes a long time for onDestory() to be called that seems to be the case). You might want to monitor your service for incoming activity that might be preventing the service from shutting down in a timely manner.