When to use a Service or AsyncTask or Handler?

18,449

Solution 1

My rule of thumb is that an AsyncTask is for when I want to do something tied to single Activity and a Service is for when I want to do something that will carry on after the Activity which started it is in the background.

So if I want to do a small bit of background processing in the Activity without tying up the UI I'll use an AsyncTask. I'll then use the default Handler from that Activity to pass messages back to ensure updates happen on the main thread. Processing the updates on the main thread has two benefits: UI updates happen correctly and you don't have to worry so much about synchronisation problems.

If for example, I wanted to do a download which might take a while I'd use a Service. So if I went to another Activity in my application or another application entirely my Service could keep running and keep downloading the file so it would be ready when I returned to my application. In this case I'd probably use a Status Bar Notification once the download was complete, so the user could choose to return to my application whenever was convenient for them.

What you'll find if you use an AsyncTask for a long-running process it may continue after you've navigated away from the Activity but:

  • If the Activity is in the background when your processing is complete you may have problems when you try to update the UI with the results etc.
  • A background Activity is far more likely to be killed by Android when it needs memory than a Service.

Solution 2

Use Service when you've got something that has to be running in the background for extended periods of time. It's not bound to any activity. The canonical example is a music player.
AsyncTask is great when some stuff has to be done in background while in the current activity. E.g. downloading, searching for text inside a file, etc.
Personally I use Handlers only to post changes to the UI thread. E.g. you do some computations in a background thread and post the result via handler.

The bottom line: in most cases, AsyncTask is what you need.

Solution 3

To complement the other answers here regarding the distinction between service and AsyncTask, it is also worth noting[0]:

  • A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
  • A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).

Services tend to be things that describes a significant part of your application - rather than an AsyncTask which is typically contributes to an Activity and/or improves UI responsiveness. As well as improving code clarity Services can also be shared with other applications, providing clear interfaces between your app and the outside world.

Rather than a book I would say the developer guide has lots of good answers.

[0] Source: http://developer.android.com/reference/android/app/Service.html#WhatIsAService

Solution 4

  • AsyncTask: When I wish to do something without hanging the UI & reflect the changes in the UI.

E.g.: Downloading something on Button Click, remaining in the same activity & showing progress bar/seekbar to update the percentage downloaded. If the Activity enters the background, there are chances of conflict.

  • Service: When I wish to do something in the background that doesn’t need to update the UI, use a Service. It doesn’t care whether the Application is in the foreground or background.

E.g.: When any app downloaded from Android Market shows notification in the Status Bar & the UI returns to the previous page & lets you do other things.

Solution 5

Service

A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with.

When to use?

Task with no UI, but shouldn’t be too long. Use threads within service for long tasks. Long task in general.

Trigger: Call to method onStartService()

Triggered from: Any Thread

Runs on: Main thread of its hosting process. The service does not create its own thread and does not run in a separate process (unless you specify otherwise)

Limitations / Drawbacks: May block main thread


AsyncTask

AsyncTask enables the proper and easy use of the UI thread. This class allows performing background operations and publishing results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.

When to use?

Small task having to communicate with main thread For tasks in parallel use multiple instances OR Executor Disk-bound tasks that might take more than a few milliseconds

Trigger: Call to method execute()

Triggered from: Main Thread

Runs on: Worker thread. However, Main thread methods may be invoked in between to publish progress.

Limitations / Drawbacks:

  • One instance can only be executed once (hence cannot run in a loop)
  • Must be created and executed from the Main thread

Ref Link

Share:
18,449
TIMEX
Author by

TIMEX

Updated on June 04, 2022

Comments

  • TIMEX
    TIMEX almost 2 years

    Can someone tell me the TRUE difference?

  • IgorGanapolsky
    IgorGanapolsky about 12 years
    You actually prefer Handlers to update the UI thread vs. AsyncTasks?
  • curioustechizen
    curioustechizen about 12 years
    This answer really nailed it. The last bit about the problems that might occur if using an AsyncTask- that is the clincher while deciding between using an AsyncTask or a Service. I think the first limitation can still be worked around - instead of updating the UI directly from the AsyncTask, do what you'd do if you were in a Service (broadcast an intent, show a notification, or insert the data into a ContentProvider to be picked up by the Activity later). However, the second point - the one about the Activity far more likely to be killed - that's the most pertinent point.
  • curioustechizen
    curioustechizen about 12 years
    Note that it is not necessary for an AsyncTask to update UI. So - the use case that you mentioned for Service can also be achieved using an AsyncTask : Just don't update the UI in the onProgressUpdate() or onPostExecute() methods.