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);
            // ...
        }
    }
}




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads