Reputation: 28188
I have an AsyncTask
with an indeterminate ProgressBar
that typically executes very quickly, but occasionally slowly. It's undesirable and distracting to for the the progress bar to flash quickly when there is no discernible wait.
Is there a way to delay display of the progress bar without creating another nested AsyncTask
?
Upvotes: 5
Views: 3230
Reputation: 28188
Thanks to Code Droid, I was able to write an abstract AsyncTask
class that shows an indeterminate progress bar after a specified delay. Just extend this class instead of AsyncTask
and be sure to call super()
when appropriate:
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();
}
};
}
Upvotes: 3
Reputation: 10472
Yes, there is and it's called a CountDownTimer and its highly underused. You can take action at each tick of the timer or when the timer runs out.
Upvotes: 4
Reputation: 2667
I am assuming you are calling onProgressUpdate at least a few times before your AsyncTask is finished. If that is the case, what you could do is this. Each time before you call onProgressUpdate, call Thread.sleep(250). This way your background Thread will pause before communicating with the UI Thread and give the appearance of a longer running task. Failing that, I'd probably need to see your code or get some more info.
Upvotes: 0