Q)Explain Service vs intent service ?
When to use?
- The Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must use threads within Service.
- The IntentService can be used in long tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. Another case of use is when callbacks are needed (Intent triggered tasks).
How to trigger?
- The Service is triggered calling to method onStartService().
- The IntentService is triggered using an Intent, it spawns a new worker thread and the method onHandleIntent() is called on this thread.
Triggered From
- The Service may be triggered from any thread.
- The IntentService must be triggered from Main Thread.
Runs On
- The Service runs in background but it runs on the Main Thread of the application.
- The IntentService runs on a separate worker thread.
Limitations / Drawbacks
- The Service may block the Main Thread of the application.
- The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially.
q) Difference between Service , Thread , IntentService, 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). | - Long 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