How can I show a progress bar only after a minimal delay?

I have AsyncTaskwith indefinite ProgressBar, which usually runs very fast, but sometimes slowly. This is undesirable and distracts attention to the fact that the progress bar will quickly flash when there is no noticeable expectation.

Is there a way to delay displaying the progress bar without creating another nested one AsyncTask?

+5
source share
3 answers

Thanks to Code Droid, I was able to write an abstract AsyncTaskclass that shows an indefinite progress bar after a specified delay. Just add this class instead AsyncTaskand be sure to call super()if necessary:

public abstract class AsyncTaskWithDelayedIndeterminateProgress
      <Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {
   private static final int MIN_DELAY = 250;
   private final ProgressDialog progressDialog;
   private final CountDownTimer countDownTimer;

   protected AsyncTaskWithDelayedIndeterminateProgress(Activity activity) {
      progressDialog = createProgressDialog(activity);
      countDownTimer = createCountDownTimer();
   }

   @Override protected void onPreExecute() {
      countDownTimer.start();
   }

   @Override protected void onPostExecute(Result children) {
      countDownTimer.cancel();
      if(progressDialog.isShowing())
         progressDialog.dismiss();
   }

   private ProgressDialog createProgressDialog(Activity activity) {
      final ProgressDialog progressDialog = new ProgressDialog(activity);
      progressDialog.setIndeterminate(true);
      return progressDialog;
   }

   private CountDownTimer createCountDownTimer() {
      return new CountDownTimer(MIN_DELAY, MIN_DELAY + 1) {
         @Override public void onTick(long millisUntilFinished) { }

         @Override public void onFinish() {
            progressDialog.show();
         }
      };
   }
+3
source

Yes, there is and it is called CountDownTimer and it is underused. You can take action at every tick of the timer or at the end of the timer.

+4
source

I assume that you call onProgressUpdate at least several times before your AsyncTask is completed. If so, then you can do it. Each time before you call onProgressUpdate, call Thread.sleep (250). Thus, your background thread is paused before exchanging information with the user interface thread and will give an idea of ​​longer work. Otherwise, I probably will need to see your code or get more information.

0
source

All Articles