Who is the "client" of a Service - a Context, or a ServiceConnection?

336 Views Asked by At

I have found and read various posts here on SO that mention you should use getApplicationContext() when binding to a Service - instead of this (in an Activity) or getActivity() (in a Fragment).

However, this raised the following question for me: The documentation repeatedly talks about the "clients" of a Service, e.g.: "When a service is unbound from all clients, the Android system destroys it" (http://developer.android.com/guide/components/bound-services.html).

What is meant by client in this context:

  • the Context that was used to call bindService()
  • or the ServiceConnection that was supplied to bindService()

Let's suppose I have two Fragments that bind to the same Service - using the Application Context and each with its own ServiceConnection.

When will the Service be destroyed?

If my second interpretation is true the Service would be destroyed when all connections are closed, i.e. when each Fragment has called getActivity().getApplicationContext().unbindService(mConnection). If the first one is true it should be closed as soon as the first Fragment makes that call because that would "unbind the Application Context"...

So, which interpretation is true? (I hope it's the second one...)

1

There are 1 best solutions below

0
On BEST ANSWER

You use getApplicationContext() so that the ServiceConnection survives e.g. Activity orientation changes (the activity gets destroyed and recreated and so does it's context). According to documentation the service might disconnect when the activity is stopped (not destroyed).

The 'client' is anyone who holds an active ServiceConnection. When nobody is connected to the service it is no longer needed and therefore destroyed (unless also started by startService(...)). The ServiceConnections are counted not the contexts.

I haven't tested whether the connection closes automatically if said Fragment is destroyed. My guess is NO, because the application context survives - you have to unbind explicitly in onDestroy.