AsyncTask is an abstract class in Android that offers us the freedom to execute demanding tasks in the background while keeping the UI thread light and the application responsive. When launched, an Android application operates in a single thread. Due to this single-thread approach, tasks that take a long time to fetch a response may cause the program to become unresponsive. We use Android AsyncTask to perform these heavy tasks in the background on a separate thread and return the results back to the UI thread in order to prevent this. As a result, the UI thread is always responsive when AsyncTask is used in an Android application.
The purpose of AsyncTask was to make it possible to use the UI thread correctly and conveniently. The most frequent use case, however, was UI integration, which led to Context leaks, missed callbacks, or crashes when settings changed. Additionally, it behaves differently depending on the platform version, swallows exceptions from doInBackground, and offers little benefit over using Executors directly. AsyncTask is not intended to be a general-purpose threading system; rather, it is intended to be a helper class for Thread and Handler. AsyncTasks are best used for brief operations (a few seconds at the most.) It is strongly advised that you use the various APIs offered by the java.util.concurrent package, such as Executor, ThreadPoolExecutor, and FutureTask, if you need to keep threads running for extended periods of time.
Asynchronous tasks are divided into three generic types: Params, Progress, & Result and four steps: onPreExecute, doInBackground, onProgressUpdate, & onPostExecute. The following lists the three generic types utilized in an Android AsyncTask class:
- Params: Parameters sent to the task upon execution
- Progress: Progress units shared during the background computation
- Result: Result obtained from the background computation
The following definitions outline the fundamental methods used in an Android AsyncTask class:
- doInBackground(): The code that has to be run in the background is contained in the doInBackground() method. The publishProgress() method in this method allows us to repeatedly deliver results to the UI thread. We only need to use the return statements to signal that the background processing has been finished.
- onPreExecute(): The code that runs prior to the beginning of the background processing is contained in this function.
- onPostExecute(): After the doInBackground method has finished processing, the onPostExecute() method is called. This method receives the output of the doInBackground method as its input.
- onProgressUpdate(): This method can use the progress updates it receives from the publishProgress method, which publishes progress updates from the doInBackground function, to update the UI thread.
AsyncTask Example
The following code snippet must be present in the MainActivity class in order to launch an AsyncTask.
MyTask myTask = new MyTask();
myTask.execute();
The execute method is used to start the background thread in the excerpt above, where we've used a sample class name that extends AsyncTask.
Kotlin
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val myTask = MyTask()
myTask.execute(10)
}
class MyTask {
override fun onPreExecute() {
super.onPreExecute()
// ...
}
override fun doInBackground(vararg params: Void?): String? {
// ...
}
override fun onProgressUpdate(values: Int?) {
super.onProgressUpdate(values);
// ...
}
override fun onPostExecute(result: String?) {
super.onPostExecute(result)
// ...
}
}
}
Java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ExampleAsync task = new ExampleAsync;
task.execute(10);
}
private static class ExampleAsync extends AsyncTask<Integer, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// ...
}
@Override
protected String doInBackground(Integer... integers) {
// ...
return "Finished!";
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// ...
}
@Override
protected void onPostExecute(String string) {
super.onPostExecute(string);
// ...
}
}
}
Similar Reads
OOPs Concepts in Android
Object-oriented programming (OOP) is a programming paradigm that is based on the concept of "objects", which can contain data and code that manipulates that data. In Android, Java is the primary programming language used for developing Android apps. Java is an object-oriented language and it provide
8 min read
Button in Android
In Android applications, a Button is a user interface that is used to perform some action when clicked or tapped. It is a very common widget in Android and developers often use it. This article demonstrates how to create a button in Android Studio.Class Hierarchy of the Button Class in Kotlinkotlin.
3 min read
Clipboard in Android
Android's Clipboard performs copying and pasting on different data types, such as text strings, images, binary stream data, and other complex data types. Clipboard does the copying and pasting operations within the same application and between multiple applications that have implemented the clipboar
5 min read
Android Sensors with Example
In our childhood, we all have played many android games like Moto Racing and Temple run in which by tilting the phone the position of the character changes. So, all these happen because of the sensors present in your Android device. Most Android-powered devices have built-in sensors that measure mot
4 min read
MediaPlayer Class in Android
MediaPlayer Class in Android is used to play media files. Those are Audio and Video files. It can also be used to play audio or video streams over the network. So in this article, the things discussed are:MediaPlayer State diagramCreating a simple audio player using MediaPlayer API. Have a look at t
4 min read
Event Handling in Android
Events are the actions performed by the user in order to interact with the application, for e.g. pressing a button or touching the screen. The events are managed by the android framework in the FIFO manner i.e. First In - First Out. Handling such actions or events by performing the desired task is c
5 min read
Android Studio Main Window
Android Studio is the official IDE (Integrated Development Environment) for Android app development and it is based on JetBrainsâ IntelliJ IDEA software. Android Studio provides many excellent features that enhance productivity when building Android apps, such as: A blended environment where one can
4 min read
Dynamic Spinner in Android
Many times in android applications we have to create any view dynamically without writing any XML code. For that, we can create our view using our Kotlin or Java file. In this article, we will take a look at How to Dynamically create a spinner in an android application. A sample video is given below
6 min read
Settings Panels in Android
With the release of Android Q by Google, a slew of new features have emerged. Location Service use is one wonderful feature, among others. In this article, we will focus on three Settings choices in particular. Internet connectivity (particularly Wifi): It displays the settings panels for Mobile dat
3 min read
Task and Back Stack in Android
When doing a job, users engage with a task, which is a set of actions. The activities are stacked in the order in which they are opened in a stack called the back stack. One action in an email app, for example, maybe to display a list of fresh messages. When the user picks a message, a new activity
8 min read