dwarvesf / til

Today I Learned. Our knowledge hub. List out what we've learned everyday, organized.
29 stars 1 forks source link

StopService does not call onDestroy immediately #10

Open nambv opened 7 years ago

nambv commented 7 years ago

http://stackoverflow.com/questions/20945847/stopservice-does-not-call-ondestroy-immediately

In my case, I followed the tutorial at Android Developers, which uses a ServiceConnection. In the example code, they call unbindService() but never stopService(). So I added a call to stopService() to stop it, but still onDestroy() never got called.

From the documentation of Context.stopService():

Note that if a stopped service still has ServiceConnection objects bound to it with the BIND_AUTO_CREATE set, it will not be destroyed until all of these bindings are removed.
I interpreted this as it's okay to call stopService() or stopSelf() first, and then unbindService() afterwards (I'm using BIND_AUTO_CREATE) - and that the service would be stopped/destroyed upon calling unbindService().

But it turns out that this isn't the case. When I moved things around so that I'm calling unbindService() first and stopService() after that, my onDestroy() gets called immediately.