How to:‎ > ‎

AsyncTasks with ProgressDialogs

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

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:
    invoked in the UI thread directly when AsyncTask is executed
    invoked directly after onPreExecute() completes
    this method can call publishProgress(Progress...) which will be caught by onProgressUpdate(Progress...) and     after will return to doInBackground
    invoked in the UI thread after a call to publishProgress(Progress...) in the doInBackground(Params...) method
    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 are as simple as this:

ProgressDialog dialog = new ProgressDialog(context);

void show() {

void hide() {

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