Reputation: 1168
In one case, one service
being started by another component runs on the main UI thread of that component, while the service may live even that component is destroyed, so my question is where to execute the service
if the component started that service
is stopped?
Upvotes: 0
Views: 791
Reputation: 7965
Typically, when you call startService()
, the service will remain running until you call stopService()
from another component or stopSelf()
from the service itself. And onStartCommand()
will always run on UI thread.
If the service is running, subsequent calls to startService()
will not create another instance of your service but run onStartCommand()
again on the running one. This is slightly different if you are binding your component to a service. In this case, the service is automatically destroyed when you unbind all components. For more details on this, see: http://developer.android.com/guide/components/services.html#Lifecycle.
In addition, note that there different ways to keep a service running, depending on what you return from the onStartCommand()
:
START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them.
To answer your question specifically, where and how to start your service depends on what exactly you want to do with it. If the component that started the service stopped, it is up to you to either 1) get a new reference to the service from another component and stop it or 2) stop the service from the service itself. But the service won't stop because the component did. Unless you are binding it to the service.
Upvotes: 2