Using AsyncTask in Android

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

This tutorial will show you how to use AsyncTask in your app.

Step 1: Create a subclass of AsyncTask

To use AsyncTask you first need to create a subclass of AsyncTask overriding at least the doInBackground(Params…) method.
The following code shows how to create an AsyncTask subclass and override the doInBackground() method:

    // AsyncTask<Params,Progress,Result> takes in three parameters
    // Params:- the type of parameters passed to the task 
        // at the time of execution
    // Progress :- the type of the progress units 
        // published during the background computation.
    // Result :- The type of result returned.
    // Its not necessary for AsyncTask to use these parameters 
        // that is if no parameters are required you could use Void to specify that 
        // Ex : AsyncTask<Void,Integer,String> or AsyncTask<Void,Void,Void>
    private class BackgroundTask extends AsyncTask<Integer,Void,String>{

        @Override
        protected String doInBackground(Integer... params) {
            //the work to be done in background comes here


            //return the result
            return null;
        }
    }

AsyncTask Subclass

Step 2: Override other methods as per requirement

There are 3 more methods that you could override as per your requirement. Those are:-
1.) onPreExecute()
2.) onProgressUpdate(Progress…)
3.) onPostExecute(Result)

The following sample code shows and explains each of the methods work and how to override them:


@Override protected void onPreExecute() { // this method is called before the doInBackground() method // here you could probably initialize variables or do any other stuff // required by the doInBackground() method // ex:- var =0; } @Override protected void onProgressUpdate(Void... values) { // this method is called every time publishProgress() method is invoked // during the doInBackground() method execution // you could put here the code to do things that are to be done while execution // of long running operation // For example updating a textview } @Override protected void onPostExecute(String s) { // this gets called when the doInBackground() method has completed execution // you could use this method to update your UI thread // for example you could update a textview with the resulting string // Ex : tvAns.setText(s); }

Override Methods

Step 3: Starting the AsyncTask from your main activity

Once created an AsyncTask can be easily executed by creating a new instance and calling the execute() method on it from the main UI activity. And passing the params required.
The following sample code shows this :

        //Creating an instance and calling execute()
        BackgroundTask bTask = new BackgroundTask();
        bTask.execute(100);

Execute

Sample Activity that uses AsyncTask

The following sample code of an activity can give a clear understanding of how to use AsyncTask. It uses AsyncTask to make a 20 sec timer such that a TextView is updated after every second, displaying the seconds elapsed.


import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView tvShowTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvShowTime = (TextView) findViewById(R.id.tvShowTime); BackgroundTask bTask = new BackgroundTask(); bTask.execute(20000); } private class BackgroundTask extends AsyncTask<Integer,Integer,String>{ @Override protected String doInBackground(Integer... params) { //the work to be done in background comes here int total = params[0]/1000; String time = "" + total; for(int i=0;i<total;i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } finally { publishProgress((i+1)); } } //return the result return time; } @Override protected void onPreExecute() { // this method is called before the doInBackground() method // here you could probably initialize variables or do any other stuff // required by the doInBackground() method // ex:- var =0; tvShowTime.setText("AsyncTask Started"); } @Override protected void onProgressUpdate(Integer... value) { // this method is called everytime publishProgress() method is invoked // during the doInBackground() method execution // you could put here the code to do things that are to be done while execution // of long running operation // For example updating a textview tvShowTime.setText(value[0]+" seconds elapsed"); } @Override protected void onPostExecute(String s) { // this gets called when the doInBackground() method has complete execution // you could use this method to update your ui thread // for example you could update a textview with the resulting string // Ex ; tvAns.setText(s); tvShowTime.setText(s+" sec elapsed \nAsyncTask Completed" ); } } }

This content has been helpful to you?

Thanks for contributing!

Yes No