Open In App

AsyncTasks in Android

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:

The following definitions outline the fundamental methods used in an Android AsyncTask class:



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.




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




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


Article Tags :