开发者

lifecycle of Service that is started and bound?

I am confused about Service lifecycle.

I have many questions following:

  1. If my app calls startService() multiple times to a Service, will there be multiple Services running simultaneously? Or only one?

  2. As 1st, if I call bindService() multiple times to a Service in my app, what will happen to my app?

  3. Assume that I have a Service that has been started via startServ开发者_StackOverflow中文版ice(), and then later I bind it in order to instruct it to do something. in this case, if I instruct (via this Binder interface) the Service to execute its stopSelf() method, does the running Service stop immediately?

  4. Assume again that I have a Service that can be started only by bindService(), and the onUnbind is overridden to return true, in this case, should I call stopSelf method explicitly to shutdown the Service?


  1. Only a single instance of a Service exists on an Android device. Started services are started only once, other start calls will result in repeated calls of onStartCommand, but won't start new instances of the same service.

  2. If you start a bound service by binding to it, and this is the first use of the service, a new instance will be created and the onBind method will be called.

  3. Yes. However threads started by the service and listeners registered by the service will be leaked. You should take care of these resources on the onDestroy method.

  4. No need to call stop self. When the last user unbinds from the service, the service is destroyed automatically.


Yes, you can run multiple services simultaneously. But if you are using a service, you have to do so with care. If you are starting a service, you have to stop that service on any method like onDestroy() or custom method, because whenever you finish your activity, the service is still running in background.

One more thing: use service only when you need background process like media player; otherwise, you can achieve all these with activity.

For more information read the Android developer service document.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜