AsyncTask (asynchronous task) is an Android class that makes it easier to do operations on a background thread and publish the result on the User Interface (UI)/ main thread without having to manipulate threads and handlers ourselves.
In Android, updating a UI from a separate thread is a frequently encountered scenario. It’s so frequent that Android provides ready to use API for such kinds of scenarios. AsyncTask is basically an API.
AsyncTask is defined by three generic types. These are called Params, Progress, and Result. AsyncTask has four methods that are called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
Example: Downloading, etc.
AsyncTask has four different types of methods to make sure you are able to do long tasks in a way that you do not do in the main thread.
These methods are as follows:
>onPreExecute() - This part of the method gets executed on the main thread. Before doing a background operation you should show something on-screen like a progress bar or an animation to the user.
>doInBackground(Params) - This method is used to do background operations on the background thread. Operations in doInBackground() method should not touch on any main thread activities or fragments.
>onProgressUpdate(Progress…) - This method receives progress updates from the doInBackground method and runs on the UI thread. This method is used to display progress bars in the UI.
>onPostExecute(Result) - In this method you can update the UI of the background operation result.
>TypeOfVarArgParams - This contains information about what type of params are used for execution.
>ProgressValue - This contains information about progress units. While doing background operations we can update information on the UI using the onProgressUpdate() method.
>ResultValue - This contains information about result type.
Example
activitymain.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical" tools:context=".MainActivity"> <EditText android:id="@+id/etNrTimes" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Enter nr of times to roll dice" android:gravity="center_vertical" android:inputType="number" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp"/> <Button android:id="@+id/btnRollDice" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:text="Roll Dice"/> <TextView android:id="@+id/tvResults" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:text="TextView"/> </LinearLayout>
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package com.example.asyntask;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
TextView tvResults;
Button btnRollDice;
EditText etNrTimes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etNrTimes = (EditText) findViewById(R.id.etNrTimes);
tvResults = (TextView) findViewById(R.id.tvResults);
btnRollDice = (Button) findViewById(R.id.btnRollDice);
tvResults.setVisibility(View.GONE);
btnRollDice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int nrOfTimes = Integer.parseInt(etNrTimes.getText()
.toString()
.trim());
new ProcessDiceInBackground()
.execute(nrOfTimes);
}
});
}
public class ProcessDiceInBackground extends AsyncTask < Integer, Integer, String > {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(Integer.parseInt(etNrTimes.getText()
.toString()
.trim()));
dialog.show();
}
@Override
protected String doInBackground(Integer...integers) {
int ones = 0, two = 0, threes = 0, fours = 0, fives = 0, sixes = 0, randomNumber;
Random random = new Random();
String results;
double currentProgress = 0;
double previousProgress = 0;
for (int i = 0; i < integers[0]; i++) {
currentProgress = (double) i / integers[0];
if (currentProgress - previousProgress >= 0.03) {
publishProgress(i);
previousProgress = currentProgress;
}
randomNumber = random.nextInt(6) + 1;
switch (randomNumber) {
case 1:
ones++;
break;
case 2:
two++;
break;
case 3:
threes++;
break;
case 4:
fours++;
break;
case 5:
fives++;
break;
default:
sixes++;
}
}
results = "Results: \n1:" + ones + "\n2:" + two + "\n3" + threes + "\n4" + fours +
"\n5" + fives + "\n6" + sixes;
return results;
}
@Override
protected void onProgressUpdate(Integer...values) {
super.onProgressUpdate(values);
dialog.setProgressStyle(values[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
dialog.dismiss();
tvResults.setText(s);
tvResults.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Process done!", Toast.LENGTH_SHORT)
.show();
}
}
}
Output: