I am confused about Service lifecycle.
I have many questions following:
If my app calls startService()
multiple times to a Service, will there be multiple Services running simultaneously? Or only one?
As 1st, if I call bindService()
multiple times to a Service in my app, what will happen to my app?
Assume that I have a Service that has been started via startService()
, 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?
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?
Started services run until they are stopped or destroyed and do not inherently provide a mechanism for interaction or data exchange with other components. Bound services, on the other hand, provide a communication interface to other client components and generally run until the last client unbinds from the service.
There are three ways of creating bound services: First is by extending the binder class. Second is by using a messenger. Third, is by using AIDL or Android Interface Definition Language.
Starting a service You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService() . The Android system calls the service's onStartCommand() method and passes it the Intent , which specifies which service to start.
Binding to a started service That is, you can start a service by calling startService() , which allows the service to run indefinitely, and you can also allow a client to bind to the service by calling bindService() .
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.
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.
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.
No need to call stop self. When the last user unbinds from the service, the service is destroyed automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With