Service is like an Activity but has no interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service.
A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this, but read further.
An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are two methods that run on UI thread, which is good to update UI components.
I am using Services, AsyncTasks frequently. Thread less, or not at all, as I can do almost everything with AsyncTask.
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.
(Update)- If communication is required, can use main thread handler or broadcast intents - 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
onStartService() |
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 /
Drawbacks |
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 |
No comments:
Post a Comment