A Service is meant to run your task independently of the Activity
, it allows you to run any task in background. This run on the main UI thread so when you want to perform any network or heavy load operation then you have to use the Thread
there.
Example : Suppose you want to take backup of your instant messages daily in the background then here you would use the Service
.
Threads
is for run your task in its own thread instead of main UI thread. You would use when you want to do some heavy network operation like sending bytes to the server continuously, and it is associated with the Android components. When your component destroy who started this then you should have stop it also.
Example : You are using the Thread
in the Activity for some purpose, it is good practice to stop it when your activity destroy.
Service |
Thread |
IntentService |
AsyncTask |
|
When to use ? |
– Task with no UI, but shouldn’t be too long. Use threads within service for long tasks. |
– Long task in general. – For tasks in parallel use Multiple threads (traditional mechanisms) |
– Long task usually with no communication to main thread. – When callbacks are needed (Intent triggered tasks). |
– Small task having to communicate with main thread. – For tasks in parallel use multiple instances OR Executor |
Trigger |
Call to method |
Thread start() method |
Intent |
Call to method execute() |
Triggered From (thread) |
Any thread |
Any Thread |
Main Thread (Intent is received on main thread and then worker thread is spawed) |
Main Thread |
Runs On (thread) |
Main Thread |
Its own thread |
Separate worker thread |
Worker thread. However, Main thread methods may be invoked in between to publish progress. |
Limitations / |
May block main thread |
– Manual thread management – Code may become difficult to read |
– Cannot run tasks in parallel. – Multiple intents are queued on the same worker thread. |
– one instance can only be executed once (hence cannot run in a loop) – Must be created and executed from the Main thread |
References:
http://www.onsandroid.com/2011/12/difference-between-android.html