Android Comparisons: Service, IntentService, AsyncTask & Thread

Service

  • Service used to perform task with no UI, task should not be long running. Use threads within service for long tasks.
  • To trigger call method onStartService().
  • Any thread can trigger.
  • Runs on main thread.It may block main thread.

Thread

  • Thread can be used for long running task.
  • For tasks in parallel use multiple threads (traditional mechanisms).
  • To trigger call thread start() method.
  • Need to manage thread manually.
  • Any thread can start.

IntentServie

  • IntentService used for long running task usually with no communication to main thread.
  • Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
  • To use it, extend IntentService and implement onHandleIntent(Intent).
  • IntentService will receive the Intents, launch a worker thread.only one request will be processed at a time.
  • To communicate with main thread, Thread can use main thread handler or broadcast. intents.
  • Intent is received on main thread and then worker thread is spawed.
  • Multiple intents are queued on the same worker thread.

AsyncTask

  • This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
  • one instance can only be executed once. We cannot call execute method on same object.
  • Must be created and executed from the Main thread.
  • For tasks in parallel use multiple instances OR Executor.
Advertisements

One thought on “Android Comparisons: Service, IntentService, AsyncTask & Thread

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s