Android AsyncTask Tutorial with Examples
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).
Android AsyncTask Javadocs:See also:
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
- Configure Android Emulator in Android Studio
- Android ToggleButton Tutorial with Examples
- Create a simple File Finder Dialog in Android
- Android TimePickerDialog Tutorial with Examples
- Android DatePickerDialog Tutorial with Examples
- What is needed to get started with Android?
- Install Android Studio on Windows
- Install Intel® HAXM for Android Studio
- Android AsyncTask Tutorial with Examples
- Android AsyncTaskLoader Tutorial with Examples
- Android Tutorial for Beginners - Basic examples
- How to know the phone number of Android Emulator and change it
- Android TextInputLayout Tutorial with Examples
- Android CardView Tutorial with Examples
- Android ViewPager2 Tutorial with Examples
- Get Phone Number in Android using TelephonyManager
- Android Phone Call Tutorial with Examples
- Android Wifi Scanning Tutorial with Examples
- Android 2D Game Tutorial for Beginners
- Android DialogFragment Tutorial with Examples
- Android CharacterPickerDialog Tutorial with Examples
- Android Tutorial for Beginners - Hello Android
- Using Android Device File Explorer
- Enable USB Debugging on Android Device
- Android UI Layouts Tutorial with Examples
- Android SMS Tutorial with Examples
- Android SQLite Database Tutorial with Examples
- Google Maps Android API Tutorial with Examples
- Android Text to Speech Tutorial with Examples
- Android Space Tutorial with Examples
- Android Toast Tutorial with Examples
- Create a custom Android Toast
- Android SnackBar Tutorial with Examples
- Android TextView Tutorial with Examples
- Android TextClock Tutorial with Examples
- Android EditText Tutorial with Examples
- Android TextWatcher Tutorial with Examples
- Format Credit Card Number with Android TextWatcher
- Android Clipboard Tutorial with Examples
- Create a simple File Chooser in Android
- Android AutoCompleteTextView and MultiAutoCompleteTextView Tutorial with Examples
- Android ImageView Tutorial with Examples
- Android ImageSwitcher Tutorial with Examples
- Android ScrollView and HorizontalScrollView Tutorial with Examples
- Android WebView Tutorial with Examples
- Android SeekBar Tutorial with Examples
- Android Dialog Tutorial with Examples
- Android AlertDialog Tutorial with Examples
- Android RatingBar Tutorial with Examples
- Android ProgressBar Tutorial with Examples
- Android Spinner Tutorial with Examples
- Android Button Tutorial with Examples
- Android Switch Tutorial with Examples
- Android ImageButton Tutorial with Examples
- Android FloatingActionButton Tutorial with Examples
- Android CheckBox Tutorial with Examples
- Android RadioGroup and RadioButton Tutorial with Examples
- Android Chip and ChipGroup Tutorial with Examples
- Using image assets and icon assets of Android Studio
- Setting SD Card for Android Emulator
- ChipGroup and Chip Entry Example
- How to add external libraries to Android Project in Android Studio?
- How to disable the permissions already granted to the Android application?
- How to remove applications from Android Emulator?
- Android LinearLayout Tutorial with Examples
- Android TableLayout Tutorial with Examples
- Android FrameLayout Tutorial with Examples
- Android QuickContactBadge Tutorial with Examples
- Android StackView Tutorial with Examples
- Android Camera Tutorial with Examples
- Android MediaPlayer Tutorial with Examples
- Android VideoView Tutorial with Examples
- Playing Sound effects in Android with SoundPool
- Android Networking Tutorial with Examples
- Android JSON Parser Tutorial with Examples
- Android SharedPreferences Tutorial with Examples
- Android Internal Storage Tutorial with Examples
- Android External Storage Tutorial with Examples
- Android Intents Tutorial with Examples
- Example of an explicit Android Intent, calling another Intent
- Example of implicit Android Intent, open a URL, send an email
- Android Services Tutorial with Examples
- Android Notifications Tutorial with Examples
- Android DatePicker Tutorial with Examples
- Android TimePicker Tutorial with Examples
- Android Chronometer Tutorial with Examples
- Android OptionMenu Tutorial with Examples
- Android ContextMenu Tutorial with Examples
- Android PopupMenu Tutorial with Examples
- Android Fragments Tutorial with Examples
- Android ListView Tutorial with Examples
- Android ListView with Checkbox using ArrayAdapter
- Android GridView Tutorial with Examples
Show More