Open In App

AsyncTasks in Android

Last Updated : 12 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

Android Manifest File in Android
Every project in Android includes a Manifest XML file, which is AndroidManifest.xml, located in the root directory of its project hierarchy. The manifest file is an important part of our app because it defines the structure and metadata of our application, its components, and its requirements. This file includes nodes for each of the Activities, Se
5 min read
Android | Android Application File Structure
It is very important to know about the basics of Android Studio's file structure. In this article, some important files/folders, and their significance is explained for the easy understanding of the Android studio work environment. In the below image, several important files are marked: All of the files marked in the above image are explained below
3 min read
What's Android Interface Definition Language (AIDL) in Android?
The Android Interface Definition Language (AIDL) is analogous to other IDLs you would possibly have worked with. It allows you to define the programming interface that both the client and repair agree upon so as to speak with one another using interprocess communication (IPC). Traditionally the Android way a process cannot access the memory of some
7 min read
Android | Running your first Android app
After successfully Setting up an Android project, all of the default files are created with default code in them. Let us look at this default code and files and try to run the default app created. The panel on the left side of the android studio window has all the files that the app includes. Under the java folder, observe the first folder containi
3 min read
How to Clone Android Project from GitHub in Android Studio?
Android Studio provides a platform where one can build apps for Android phones, tablets, Android Wear, Android TV, and Android Auto. Android Studio is the official IDE for Android application development, based on IntelliJ IDEA. One can develop Android Applications using Kotlin or Java as the Backend Language, and it provides XML for developing Fro
3 min read
How to Add OpenCV library into Android Application using Android Studio?
OpenCV is the huge open-source library for computer vision, machine learning, and image processing and now it plays a major role in real-time operation which is very important in today’s systems. By using it, one can process images and videos to identify objects, faces, or even the handwriting of a human. When it integrated with various libraries,
3 min read
8 Best Android Libraries That Every Android Developer Should Know
Android is an operating system which is built basically for Mobile phones. It is used for touchscreen mobile devices like smartphones and tablets. But nowadays these are utilized in Android Auto cars, TV, watches, camera, etc. Android has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bought i
5 min read
How to Add Audio Files to Android App in Android Studio?
The audio file format is a file format for saving digital audio data on a computer system and all are aware of audio files. So in this article, we are going to discuss how can we add audio files to the android app. There are three major groups of audio file formats: Format Name Description Examples Uncompressed audio formatsUncompressed audio forma
3 min read
How to Add Firebase Analytics to Android App in Android Studio?
Analytics is one of the important tools that developers should definitely used while building their applications. It is very helpful to target your apps for various audience ranges and to track on which screen the users are spending a long time. So it is one of the important features which one should not miss adding while building any Android Appli
4 min read
Different Ways to Change Android SDK Path in Android Studio
Android SDK is one of the most useful components which is required to develop Android Applications. Android SDK is also referred to as the Android Software Development Kit which provides so many features which are required in Android which are given below: A sample source code.An Emulator.Debugger.Required set of libraries.Required APIs for Android
5 min read
Article Tags :
Practice Tags :