android service startService() and bindService()

前端 未结 3 827
别跟我提以往
别跟我提以往 2020-11-30 23:45

I would like to know if it is possible to have a service that is started with startService and then be able to also bind to that service and do some remote procedure calls?

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 00:49

    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:

    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.

提交回复
热议问题