o7planning

Android AsyncTask Tutorial with Examples

  1. Android AsyncTask
  2. Example of AsyncTask

1. Android AsyncTask

The AsyncTask class has been introduced to Android since API Level 3 with the aim of providing a standard to work with UI Thread easily.
Normally, AsyncTask is used to perform a task running in the background of the application and update the status of this task in the interface during the task performance.
In some cases you use the UI to interact with AsyncTask, which poses some risks. In particular, that would cause Context leaks, missed callback(s), or crashes on configuration changes (For example, the user rotates the device screen). It also has inconsistent behavior on different versions of the platform, swallows exceptions from doInBackground, and does not provide much utility over using Executor(s) directly.
AsyncTask is designed as a helper class for Thread and Handler. It should be used for short activities (within a few seconds). If you want to have a thread running for a long time, you should use the classes provided by java.util.concurrent such as Executor, ThreadPoolExecutor and FutureTask.
AsyncTask has been introduced to Android since API Level 3 and marked "deprecated" since API Level 30 (Ạndroid 11).

2. Example of AsyncTask

In this example, we are going to use the AsyncTask to perform a task running in the background of the application and update the status of the task in the interface during its operation.
On Android Studio create a new project:
  • File > New > New Project > Empty Activity
    • Name: AsyncTaskExample
    • Package name: org.o7planning.asynctaskexample
    • Language: Java
Here is the application interface:
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView_info"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:gravity="center"
        android:text="Working info"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/progressBar" />

    <Button
        android:id="@+id/button_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="Click to Start"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView_info" />

    <Button
        android:id="@+id/button_cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Cancel"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button_start" />

</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package org.o7planning.asynctaskexample;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private ProgressBar progressBar;
    private TextView textViewInfo;
    private Button buttonStart;
    private Button buttonCancel;

    private MyWorkTask myWorkTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
        this.textViewInfo = (TextView) this.findViewById(R.id.textView_info);
        this.buttonStart = (Button) this.findViewById(R.id.button_start);
        this.buttonCancel = (Button) this.findViewById(R.id.button_cancel);

        this.buttonStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startWork();
            }
        });
        this.buttonCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestCancel();
            }
        });
    }

    private void startWork()  {
        this.myWorkTask = new MyWorkTask(this.progressBar,
                this.textViewInfo, this.buttonStart, this.buttonCancel);

        ParamInfo param = new ParamInfo("Param 1", "Param 2");

        this.myWorkTask.execute(param);
    }

    private void requestCancel()  {
        if(this.myWorkTask != null)  {
            this.myWorkTask.cancel(true);
        }
    }
}
MyWorkTask.java
package org.o7planning.asynctaskexample;

import android.os.AsyncTask;
import android.os.SystemClock;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.Date;

// <Params, Progress, Result>
public class MyWorkTask extends AsyncTask<ParamInfo, ProgressInfo, ResultInfo> {

    private final ProgressBar progressBar;
    private final TextView textViewInfo;
    private final Button buttonStart;
    private final Button buttonCancel;

    private final int PROGRESS_MAX;
    private int workCount = 0;
    private long startTimeInMillis;

    public MyWorkTask(ProgressBar progressBar, TextView textViewInfo,
                      Button buttonStart, Button buttonCancel)  {
        this.progressBar = progressBar;
        this.textViewInfo = textViewInfo;
        this.buttonStart = buttonStart;
        this.buttonCancel = buttonCancel;
        this.PROGRESS_MAX = this.progressBar.getMax();
    }

    @Override
    protected void onPreExecute() {
        this.progressBar.setVisibility(ProgressBar.VISIBLE);
        this.textViewInfo.setText("Start...");
        this.buttonStart.setEnabled(false);
        this.buttonCancel.setEnabled(true);
        this.startTimeInMillis = new Date().getTime();
    }

    @Override
    protected ResultInfo doInBackground(ParamInfo... params) {
        final int WORK_MAX = 30;

        while (this.workCount < WORK_MAX) {
            SystemClock.sleep(100); // 100 Milliseconds.
            this.workCount++;

            int progress = (this.workCount * PROGRESS_MAX) / WORK_MAX; // Progress value.
            int percent = (progress * 100) / PROGRESS_MAX;
            String info = "(" + percent +"%) - Working part " + this.workCount + " of " + WORK_MAX;

            ProgressInfo progressInfo = new ProgressInfo(progress, info);
            this.publishProgress(progressInfo); // Progress ...values
        }
        long finishTimeInMillis = new Date().getTime();
        long workTimeInMillis = finishTimeInMillis - this.startTimeInMillis;
        ResultInfo result = new ResultInfo(true, workTimeInMillis);
        return result;
    }

    @Override
    protected void onProgressUpdate(ProgressInfo... values) { // Progress ...values
        ProgressInfo progressInfo= values[0];

        int progress = progressInfo.getProgress();

        this.progressBar.setProgress(progress);
        this.textViewInfo.setText(progressInfo.getWorkingInfo());
    }

    @Override
    protected void onPostExecute(ResultInfo resultInfo) {
        super.onPostExecute(resultInfo);
        this.buttonStart.setEnabled(true);
        this.buttonCancel.setEnabled(false);
        this.textViewInfo.setText(resultInfo.getMessage());
    }

    @Override
    protected void onCancelled(ResultInfo resultInfo) {
        super.onCancelled(resultInfo);
        this.buttonStart.setEnabled(true);
        this.buttonCancel.setEnabled(false);
        this.textViewInfo.setText(resultInfo.getMessage());
    }
}
ParamInfo.java
package org.o7planning.asynctaskexample;

public class ParamInfo {
    private String param1;
    private String param2;

    public ParamInfo(String param1, String param2)  {
        this.param1 = param1;
        this.param2 = param2;
    }

    public String getParam1() {
        return param1;
    }

    public String getParam2() {
        return param2;
    }
}
ProgressInfo.java
package org.o7planning.asynctaskexample;

public class ProgressInfo {
    private int progress;
    private String workingInfo;

    public ProgressInfo(int progress, String workingInfo) {
        this.progress = progress;
        this.workingInfo = workingInfo;
    }
    public int getProgress() {
        return progress;
    }

    public String getWorkingInfo() {
        return workingInfo;
    }
}
ResultInfo.java
package org.o7planning.asynctaskexample;

public class ResultInfo {
    private boolean completed;
    private long workTimeInMillis;

    public ResultInfo(boolean completed, long workTimeInMillis) {
        this.completed = completed;
        this.workTimeInMillis = workTimeInMillis;
    }

    public boolean isCompleted() {
        return completed;
    }

    public long getWorkTimeInMillis() {
        return workTimeInMillis;
    }

    public String getMessage() {
        if(this.completed)  {
            return "Complete in " + this.workTimeInMillis +" milliseconds";
        }
        return "Failed or cancelled";
    }
}

Android Programming Tutorials

Show More