AsyncTask usage summary

AsyncTask01

Overview

AsyncTask is useful when you are working on UI (main) thread, and want to do some (maybe long) background process, and want to get callback after the background process finishes. For example, consider the case when you want to update UI of Activity according to the result of internet access. You must execute URLconnection in background thread, while updating UI must be done in UI thread after getting result. It can be implemented without caring about threads or handlers by using AsyncTask. 

Basics

4 Steps method execution flow

AsyncTask – method sequence
  1. onPreExecute: invoked on the UI thread, before doInBackground starts. Initial set up part.
  2. doInBackground: invoked on the background thread. Long computation/process (ex. downloading) is executed in this method. It must be overriden.
  3. onProgressUpdate: invoked on the UI thread, during doInBackground. It is invoked after doInBackground method calls publishProgress to update UI of background process progress.
  4. onPostExecute: invoked on the UI thread, after doInBackground finishes. Final UI update part. 

The purpose to use AsyncTask is usually updating UI according to the result of background task, so at least you usually implement 2. doInBackground (MUST) and 4. onPostExecute.
(If you only need background process and callback to main thread is not necessary, just use Thread.start() or Handler.post() )

3 Types declaration 

AsyncTask is used by extending the class to your custom Class. You need to specify 3 types when extending AsyncTask.

public class CustomAsyncTask extends AsyncTask<Params, Progress, Result> { ... }
  1. Params: input parameter, used in doInBackground method.
  2. Progress: the parameter passed from doInBackground to onProgressUpdate via publishProgress(Progress...)
  3. Result: return parameter of doInBackground,which is passed to onPostExecute.

※ If not necessary, just set Void type for each.

Usage – template

  • AsyncTask side 

Create subclass of AsyncTask. As written in Advance, it may be implemented as a inner class of Activity class.

import android.os.AsyncTask;

/**
 * AsyncTask<Params, Progress, Result>
 *     Params:   Input parameter type
 *        - arg of {@link #doInBackground}
 *
 *     Progress: Progress parameter type
 *        - arg of {@link #onProgressUpdate}
 *
 *     Result:   Return parameter from background process
 *        - return type of {@link #doInBackground}
 *        - arg of {@link #onPostExecute}
 */
public class CustomAsyncTask extends AsyncTask<Void, Void, Void> {

    private static final String TAG = CustomAsyncTask.class.getSimpleName();

    private int mParam;

    public CustomAsyncTask(int param) {
        // Constructor can be used to set field variable.
        mParam = param;
    }

    @Override
    protected void onPreExecute() {
        // Initial UI set up here (if necessary)
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Implement (maybe long) background process here!

        //publishProgress(); // If you want to update UI during this process

        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        // invoked when publishProgress() is called,
        // to update UI of progress during doInBackground is running.
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        // Finally, the result of doInBackground is handled on UI thread here.
    }
}
  • Execution side

Usually the purpose is to update the UI, so execution is done from Activity/Fragment class.

int param;

  ...

new CustomAsyncTask(param).execute();

Note that even type of “params”  is Void, the variables can be passed by Constructor. This is useful tip when you want to pass/input more than 2 types of variable.

More concrete examples

For example, refer AsyncTask Android example.

Advance

AsyncTask is usually used with Activity/Fragment, while the background task may be completely independent process from Activity itself. So the question comes up: how to establish independency between Activity & AsyncTask? which is the next topic

Reference

Leave a Comment

Your email address will not be published. Required fields are marked *