ispiro
ispiro

Reputation: 27653

Why unbind Service onDestroy?

I've seen it mentioned in multiple sources, that if an Activity binds a Service, it should unbind it onDestroy. Why? Since the Activity is destroyed, it seems like the service will be unbound anyway. If it was "started" - it doesn't matter anyway. And if it was auto-started by the activity - it will close anyway if no others bound it.

So why unbind it?

Upvotes: 6

Views: 5784

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006644

Activities need to handle configuration changes, such as when the screen is rotated, or the user changes locales, or the device enters night mode.

The default behavior of the foreground activity, when a configuration change occurs, is for it to be destroyed and recreated.

As a result, calling bindService() on an Activity is not a good idea. We want the binding to remain intact across the configuration change. Otherwise, our service will get destroyed and recreated, along with the activity (assuming that the activity has the one-and-only binding and nothing else started the service).

So, the recommended pattern is to call bindService() on the Application singleton. Then, you can pass your ServiceConnection from the old activity instance to the new activity instance. Retained fragments work great for this, as you can then call unbindService() in onDestroy() of the fragment, so that when the activity is "permanently" destroyed (e.g., user presses BACK, you call finish()), your binding can be released.


With all that as background, on to your specific concern.

First, you assume that a destroyed activity automatically unbinds from any services that it bound to via bindService() called on that Activity. It's possible that this happens, though I do not recall that being documented behavior, and it's the sort of thing that developers should not rely upon.

More importantly, in most cases, calling bindService() on the Activity is not the right approach. Otherwise, you get into the problems that I outlined above.

But, following the call-bindService()-on-the-Application pattern, I would not expect there ever to be some sort of automatic unbinding, because the Application singleton is never destroyed. So, if you fail to call unbindService() somewhere (e.g., in onDestroy() of the retained fragment), you will leak your service.

Upvotes: 10

Related Questions