android service startService() and bindService()

Yes, You can start and bind (one or more times) the same service.

The following flowchart demonstrates how the lifecycle of a service is managed. The variable counter tracks the number of bound clients: enter image description here

Good example - music app. Explanation from Building a Media Browser Service official tutorial:

A service that is only bound (and not started) is destroyed when all of its clients unbind. If your UI activity disconnects at this point, the service is destroyed. This isn't a problem if you haven't played any music yet. However, when playback starts, the user probably expects to continue listening even after switching apps. You don't want to destroy the player when you unbind the UI to work with another app.

For this reason, you need to be sure that the service is started when it begins to play by calling startService(). A started service must be explicitly stopped, whether or not it's bound. This ensures that your player continues to perform even if the controlling UI activity unbinds.

To stop a started service, call Context.stopService() or stopSelf(). The system stops and destroys the service as soon as possible. However, if one or more clients are still bound to the service, the call to stop the service is delayed until all its clients unbind.

From Service ref:

A service can be both started and have connections bound to it. In such a case, the system will keep the service running as long as either it is started or there are one or more connections to it with the Context.BIND_AUTO_CREATE flag. Once neither of these situations hold, the service's onDestroy() method is called and the service is effectively terminated.


I think hara's answer was a little confusing. What you describe is perfectly legitimate and in fact the only way to get the behavior you want. If you create a Service by binding to it, it will die when you unbind. So the only way to keep it around without activities binding to it is to start it with startService(). There is no conflict with lifecycles because it only applies to how the service is STARTED. So once it's started with startService(), it follows that lifecycle process. So you are free to bind and unbind to it as much as you wish and it will only die when you call stopService() or stopSelf().

Tags:

Android