Reputation: 866
I'm new to Android and I've been quite confused about the life time of service and thread.
Let's say I have an activity and it starts a service in a worker thread by calling startService(). According to Google documentations, the service will run indefinitely even if the calling component is destroyed.
So here's my question: if the application process is completely destroyed ( exited and cleaned from back stack ), is the service still running ? Is the UI thread still running as well ? If yes, does that mean the thread is not necessarily killed even if its calling process is destroyed ?
Upvotes: 0
Views: 134
Reputation: 10278
A Thread
is not a service. A Service
is generally declared in the manifest and has a lifecycle of its own. When it is not declared in a manifest, it can run beyond the lifecycle of an Activity but it will only run when started through a declared element in the manifest (i.e. an Activity or another Service).
You are using the terms without clearly making this distinction. Take a look a this:
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html
It helps to make the distinction among "threads" and "services." As pointed out in other answers, both a Service
and a thread
can be destroyed when the system is low on resources. However, if a thread is created from an Activity
and manages its memory properly, it will die when the Activity dies (because no references are held to it). If it keeps a reference to the Activity, it may not die, but neither will the Activity even if there is no way to return to the Activity. This is a type of memory leak and should be avoided.
Just to be clear, a Service
runs independent of an Activity
and has it's own thread. A java thread does also, but should not survive the lifespan of an Activity
that creates it.
Upvotes: 1
Reputation: 351
1 . Service can be stop by system when device low resource or low memory
2 . If your app is force stopped (by system task killer or some app with root permission) your service is also destroy unless you start app again and restart your service
3 . If your app is cleaned from back stack or exited your service is not destroyed , and thread still running , any update to UI in this time can make error
Hope this info help
Upvotes: 1
Reputation: 35
Service is not destroyed by itself. You need to call stopself() from the calling Activity. Even if the calling activity is destroyed it will not be destroyed. You can instead use IntentService, which are self destroying after finishing the work. IntentService Service
Upvotes: 0