How to:‎ > ‎

AsyncTasks with ProgressDialogs

Purpose:
Running a background thread that will update the UI through widgets such as progressdialogs

AsyncTask:
AsyncTasks are used in the place of confusing Threads and Handlers. They allow programs to run events in a background thread that will update the UI thread. They must be subclassed in a UI class and its methods must not be called directly.

AsyncTasks have a basic structure of 4 steps:
onPreExecute()
    invoked in the UI thread directly when AsyncTask is executed
doInBackground(Params...)
    invoked directly after onPreExecute() completes
    this method can call publishProgress(Progress...) which will be caught by onProgressUpdate(Progress...) and     after will return to doInBackground
onProgressUpdate(Progress...)
    invoked in the UI thread after a call to publishProgress(Progress...) in the doInBackground(Params...) method
onPostExecute(Result)
    invoked after doInBackground(Params...) completes

All methods but doInBackground can update the UI thread.

Starting an AsyncTask is as simple as calling AsyncTask.execute(Params...)

ProgressDialogs:
ProgressDialogs are as simple as this:

ProgressDialog dialog = new ProgressDialog(context);

void show() {
    dialog.setMessage(string);
    dialog.show();
}

void hide() {
    dialog.dismiss();
}

Putting them together:
To show a progress dialog while an AsyncTask runs, you may call show() in onPreExecute() and call hide() in onPostExecute(). This will start the ProgressDialog before the AsyncTask does it's background method and will stop the ProgressDialog when it completes.


by Grantland Chew 3/2/10
Comments