When to use AsyncTask
and When to use Thread
as both do work in background and both can manipulate controls in UI Thread
by some mechanism..

- 19,463
- 14
- 75
- 113

- 387
- 1
- 5
- 24
-
When you have no issue in running task parellel, for the same thing i.e. say you want to process different calculations you just start in a thread. For asyncTask when you need something to be returned from a background work, or want to wait for some process to finish before executing some other process or update some view etc. – Saqib Apr 08 '14 at 09:29
-
3Similar question answered: http://stackoverflow.com/questions/18480206/asynctask-vs-thread-in-android – greenmarker Apr 08 '14 at 09:32
-
My requirement is to hit a service and then retrieve some data and keep list of object in list and also update ui for its progress the retrieval may take time – user3048027 Apr 08 '14 at 09:44
3 Answers
May this help you:
For long-running tasks, we use Java threads, and Android's native AsyncTask.
Basically Use AsyncTask for:
- Simple network operations which do not require downloading a lot of data
- Disk-bound tasks that might take more than a few milliseconds
And Use Java threads for:
- Network operations which involve moderate to large amounts of data (either uploading or downloading)
- High-CPU tasks which need to be run in the background
- Any task where you want to control the CPU usage relative to the GUI thread
For more information refer Mohit's answer Click Here
Edit:
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. Service is access to a Context object which has an independent life cycle. This allows for reuse of common code by many activities and, in the case of public or exposed services in many applications.
A Service runs on the main thread of the calling Component’s process by default (and hence can degrade responsiveness and cause ANRs), hence you should create a new Thread to perform long running operations.
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 and stopping a thread sometime become problematic also. A thread is a mechanism for doing work without blocking other work...
A service does not imply a thread and a thread does not imply a service. Both are different from eachother..
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.

- 13,173
- 5
- 29
- 38

- 3,189
- 2
- 22
- 30
-
I'd pass the Thread class completely and go for the "new" Executor framework + Runnable/Callable+Future. – ElDuderino Apr 08 '14 at 09:45
AsyncTask is just a "helper" class provided with Android SDK to make it easier to skip to the UI thread after the background task is finished. It is built over the standard Java threading API. It does not give antyhing that cannot be done with Threads only. It addresses the common scenario of switching between the short task run background thread and UI thread.
Generally it is convenient to use AsyncTask when you must "skip back" to UI thread when the background task is done or when you have to give some feedback to UI thread during task execution. Otherwise it's just overhead.
You are not forced to use AsyncTask. If you as a developer prefer using Thread
s directly or Future
s you may use it and skip to UI thread on your own manually after the background task is done.
EDIT:
Some other answers here suggest that using AsyncTask should be limited to short tasks. Allegedly because it uses a common pool. However it is no longer true since API Level 11 (so, for quite a long time). You can use executeOnExecutor
instead of execute
to execute AsyncTask's in dedicated thread pool. See http://developer.android.com/reference/android/os/AsyncTask.html#executeOnExecutor%28java.util.concurrent.Executor,%20Params...%29
Because examples are usually more communicative look at the example below.
Let's assume that we have a static function to do some heavy task and a TextView which we want to display progress and final status of the task declared as below:
static Object doHeavyTask(String string) throws Exception;
TextView progressInfo;
Execution of the task in background thread using async task would look like:
new AsyncTask<String, Integer, Exception>() {
@Override
protected Exception doInBackground(String... params) {
for (int i = 0; i < params.length; i++) {
try {
doHeavyTask(params[i]);
} catch (Exception e) {
return e;
}
publishProgress(i, params.length);
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
progressInfo.setText("Executed " + values[0] +
" of " + values[1] + " tasks.");
}
@Override
protected void onPostExecute(Exception result) {
if (result == null) {
progressInfo.setText("Heavy background job done successfully!");
}
else {
progressInfo.setText("Heavy background job failed!" +
"Exception message: " + result.getMessage());
}
}
}.execute("input1", "input2", "input3");
Exactly the same can be achieved with Thread:
final Handler handler = new Handler(Looper.getMainLooper());
final String[] params = { "input1", "input2", "input3" };
new Thread() {
@Override
public void run() {
for (int i = 0; i < params.length; i++) {
try {
doHeavyTask(params[i]);
} catch (final Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
progressInfo.setText("Heavy background job failed!" +
"Exception message: " + e.getMessage());
}
});
return;
}
final int currentIndex = i;
handler.post(new Runnable() {
@Override
public void run() {
progressInfo.setText("Executed " + currentIndex +
" of " + params.length + " tasks.");
}
});
}
handler.post(new Runnable() {
@Override
public void run() {
progressInfo.setText(
"Heavy background job done successfully!");
}
});
}
}.start();
As you see above using the AsyncTask is simply a bit more convenient. But there is no other advantage, just this convenience :). If you prepared your own task encapsulating Thread (and a Handler to skip back to the UI thread) then maybe your class will be more efficient/comfortable for you to use. That's all :).

- 8,379
- 4
- 36
- 61
You can run multiple threads concurrently. But asynctask is queued, meaning it is running one task at a time.

- 1,248
- 4
- 18
- 31
-
3By default AsyncTask is run in serial in a single thread, but you can run it in parallel on multiple threads too. – ElDuderino Apr 08 '14 at 09:28
-
@ElDuderino and the purposes/scenarios of running asyntask in multiple thread? – twb Apr 08 '14 at 09:39
-
I don't understand the question... AsyncTasks are always run in a thread, by default in one thread (queued, in serial, not parallel), but you can run it on multiple threads too, so multiple AsyncTasks get executed on multiple threads == true parallelism. – ElDuderino Apr 08 '14 at 09:42
-
-