Managing the Lifecycle of a Bound Service
When a service is unbound from all clients, the Android system destroys it (unless it was also started with onStartCommand()
). As such, you don't have to manage the lifecycle of your service if it's purely a bound service—the Android system manages it for you based on whether it is bound to any clients.
However, if you choose to implement the onStartCommand()
callback method, then you must explicitly stop the service, because the service is now considered to be started. In this case, the service runs until the service stops itself with stopSelf()
or another component calls stopService()
, regardless of whether it is bound to any clients.
Additionally, if your service is started and accepts binding, then when the system calls your onUnbind()
method, you can optionally return true
if you would like to receive a call to onRebind()
the next time a client binds to the service. onRebind()
returns void, but the client still receives the IBinder
in its onServiceConnected()
callback. Below, figure 1 illustrates the logic for this kind of lifecycle.
Figure 1. The lifecycle for a service that is started and also allows binding.
For more information about the lifecycle of a started service, see the Services document.