2019独角兽企业重金招聘Python工程师标准>>>
As discussed in the Services document, you can create a service that is both started and bound. That is, the service can be started by calling startService()
, which allows the service to run indefinitely, and also allow a client to bind to the service by calling bindService()
.
If you do allow your service to be started and bound, then when the service has been started, the system does not destroy the service when all clients unbind. Instead, you must explicitly stop the service, by calling stopSelf()
or stopService()
.
Although you should usually implement either onBind()
or onStartCommand()
, it's sometimes necessary to implement both. For example, a music player might find it useful to allow its service to run indefinitely and also provide binding. This way, an activity can start the service to play some music and the music continues to play even if the user leaves the application. Then, when the user returns to the application, the activity can bind to the service to regain control of playback.
Be sure to read the section about Managing the Lifecycle of a Bound Service, for more information about the service lifecycle when adding binding to a started service