Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use AsyncTask and When to use Thread in Android

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..

like image 459
user3048027 Avatar asked Apr 08 '14 09:04

user3048027


People also ask

What is the difference between AsyncTask and thread?

Thread can be triggered from any thread, main(UI) or background; but AsyncTask must be triggered from main thread. Also on lower API of Android(not sure, maybe API level < 11), one instance of AsyncTask can be executed only once.

What is the difference between handler vs AsyncTask vs thread?

AsyncTask are similar, in fact, they make use of Handler , but doesn't run in the UI thread, so it's good for fetching data, for instance fetching web services. Later you can interact with the UI. Thread however can't interact with the UI, provide more "basic" threading and you miss all the abstractions of AsyncTask .

Why AsyncTask is used in Android?

This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field. onPostExecute(Result) , invoked on the UI thread after the background computation finishes.

Should I use AsyncTask?

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.


2 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.

like image 73
Bhavin Nattar Avatar answered Sep 27 '22 23:09

Bhavin Nattar


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 Threads directly or Futures 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 :).

like image 33
Tomasz Gawel Avatar answered Sep 27 '22 22:09

Tomasz Gawel