The Android ProgressDialog provides a simple visual feedback to our users, especially when it is used with a background task. However, when the task involves retrieving data from the network, the actual completion time can be unpredictable. If the task completes very quickly, displaying the progress dialog can be a UI nuisance. One of the techniques for solving this problem is to delay the dialog appearance after the background task is launched. If the task completes in less time than the delay amount, the dialog will not show up at all. In this post we show a commonly-used combination of ProgressDialog and ASyncTask with a slightly modified implementation of the standard ProgressDialog. The common technique is using a ProgressDialog within an ASyncTask is to show the dialog in onPreExecute() and dismiss it in onPostExecute()

void onPreExecute()
{
   progress = ProgressDialog.show (myContext,
                                   "Dialog Title",
                                   "Dialog Message");
}

void onPostExecute (Void unused)
{
   if (progress.isShowing())
      progress.dismiss();
}

Imagine if we can add a pre-rendering delay to our dialog by invoking the following statement (the fourth argument is a 750-millisecond delay):

   progress = DelayedProgressDialog.show (myContext,
                                   "Dialog Title",
                                   "Dialog Message", 750);

and a corresponding cancel() invocation in the onPostExecute()

void onPostExecute (Void unused)
{
   if (progress.isShowing())
      progress.dismiss();
   progress.cancel();
}

Our approach is to design a new class DelayedProgressDialog that inherits ProgressDialog and incorporates the Android Handler#postDelayed method. By using a static Handler and adding a Runnable instance to each DelayedProgressDialog the invocation of cancel() will allow the Handler to remove the appropriate runnable from its message queue. The following code is available for download from GitHub Gists