How to use asynctask in android

How to use asynctask in android

Android AsyncTask (Asynchronous Task) is an abstract class provided by Android. Here we go to see, how to use Asynctask in android. Asynctask gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive and fast.

AsyncTask class is used to do background operations that will update the UI(user interface). Mainly we used it for short operations that will not affect our main thread.

The android application runs on a single thread when launched. Due to this single thread model tasks that take a long time to fetch the response can make the application non-responsive.

To avoid this we use android AsyncTask to perform the heavy tasks in the background on a dedicated thread and passing the results back to the UI thread. Hence use of AsyncTask in the android application keeps the UI thread responsive at all times.

Sometimes, we use for getting data from the server using Asynctask in android

Asynchronous execution

When an asynchronous task is executed, the task goes through 4 steps.

AsyncTask class is firstly executed using execute() method. In the first step AsyncTask is called onPreExecute() then onPreExecute() calls doInBackground() for background processes and then doInBackground() calls onPostExecute() method to update the UI.


1. onPreExecute():

This method contains the code which is executed before the background processing starts. This invoked on the UI thread before the task is executed. This step is normally used to set up the task, for instance by showing a progress bar in the user interface.

2. doInBackground (Params...):

This method contains the code which needs to be executed in the background. In this method, we can send results multiple times to the UI thread by publishProgress() method.

To notify you that the background processing has been completed we just need to use the return statements. This invoked on the background thread immediately after onPreExecute() finishes executing.

This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step.

3. onProgressUpdate (Progress...):

This method receives progress updates from doInBackground method and runs on the UI thread, which is published via publishProgress method, and this method can use this progress update to update the UI thread.

This method is used to display any form of progress in the user interface while the background computation is still executing. You can use Progress Bar or show Toast for users.

4. onPostExecute (Result):

This method is called after doInBackground method computation finishes on the UI thread. The result of the background computation is passed to this step as a parameter. You can use the progress bar or show Toast for users.

Example Code syntax for Android AsyncTask:

private class MyAsyncTask extends AsyncTask<URL, Integer, Long> {
protected void onPreExecute() {
// update the UI before background processes start
protected Long doInBackground(URL... urls) {
// code that will run in the background
return ;
protected void onProgressUpdate(Integer... progress) {
// receive progress updates from doInBackground
protected void onPostExecute(Long result) {
// update the UI after background processes completes

In the above snippet, we’ve used a sample class name that extends Asynctask in the android, and the execute method is used to start the background thread.

  • The AsyncTask instance must be created and invoked in the UI thread.
  • The methods overridden in the AsyncTask class should never be called. They’re called automatically
  • AsyncTask can be called only once. Executing it again will throw an exception.
  • You can change the return parameter type as well as request parameter type according to your requirement.

Asynctask example in android

Now let's take an example of AsyncTask that makes a process to go to sleep for a given period of time as set by the user.

The xml layout is defined in the activity_main.xml and its given below:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
        <activity android:name=".MainActivity">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
        android:text="Welcome to Legend Blogs Exmpale"
        android:id="@+id/textView2" />
        android:text="Please enter a waiting Time"
        android:layout_marginTop="64dp" />
        android:layout_alignStart="@+id/textView" />
        android:text="Run AsyncTask"
        android:layout_marginTop="62dp" />

package com.legendblogs.asynctask;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
    Context context;
    EditText editText;
    Button button;
    protected void onCreate(Bundle savedInstanceState) {
        this.context = this;
        editText = (EditText) findViewById(;
        button = (Button) findViewById(;
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if(editText != null && editText.length() > 0)
                new MyAsyncTask(context).execute(editText.getText().toString());

package com.legendblogs.asynctask;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
 * Created by androidexec on 15-05-2018.
public class MyAsyncTask  extends AsyncTask<String, String, String> {
    Context context;
    String result;
    ProgressDialog progressDialog;
    public MyAsyncTask (Context context) {
        this.context = context;
    protected void onPreExecute() {
        progressDialog =,
                "Progress Dialog", null);
    protected String doInBackground(String... args) {
        int value = Integer.parseInt(args[0]);
        for(int i = 0; i <= value ;i++){
            try {
            } catch (Exception e) {
                Log.v("Error: ", e.toString());
            result = "Please wait for " + (value - i ) + " seconds";
        return null;
    protected void onProgressUpdate(String... text) {
    protected void onPostExecute(String result) {

In the above code, we’ve used AsyncTaskRunner class to perform the AsyncTask operations. The time in seconds is passed as a parameter to the class and a ProgressDialog is displayed for the given amount of time.

Advantages of Android AsyncTask

Android AsyncTask have many advantages for users to use this, Let's take a review on a few points:

  • Lightweight Process
  • Asynchronous execution
  • Easy to implement for heavy task
  • Custom Thread Management
  • Simple and quick

Custom Thread Management

Using the AsyncTask is the easiest and most convenient way to manage background tasks from within an Activity.

However, in cases where tasks need to be processed in parallel with more control, or the tasks need to continue executing even when the activity leaves the screen, you'll need to create a background service or manage threaded operations more manually.

Limitations of Android AsyncTask

The modern AsyncTask is limited to 128 concurrent tasks, with an additional queue of 10 tasks (if supporting Android 1.5, it’s a limit of ten tasks at a time, with a maximum queue of 10 tasks).

That means that if you queue up more than 138 tasks before they can complete, your app will crash.

An AsyncTask is tightly bound to a particular Activity. In other words, if the Activity is destroyed or the configuration changes then the AsyncTask will not be able to update the UI on completion.

As a result, for short one-off background tasks tightly coupled to updating an Activity, we should consider using an AsyncTask as outlined above.

The image given below is the outputs produced by the project where the time set by the user is 5 seconds.

asyncTask in android


  1. How to show Toast in Android
  2. Grid In Android with RecyclerView
  3. Check a Device's Network Connection

Thank you and happy coding..

Related posts
Write a comment