Add a delay to Progress Dialog

I want to make a dummy progress dialog appear for 2 or 3 seconds. It won't actually do anything other than say detecting. I have the code:

 ProgressDialog dialog = ProgressDialog.show(this, "", "Detecting...", true); dialog.show(); dialog.dismiss();

But what do I put in between the show, and the dismissal to have the dialog appear for a few seconds? Thanks!

6 Answers

The correct way - it does not block your main thread, so UI stays responsive:

dialog.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() { public void run() { dialog.dismiss(); }
}, 3000); // 3000 milliseconds delay
2
 progress.setProgress(100); Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { pdialog.dismiss(); }}, 3000);

You can also use CountDownTimer of Android which is much more efficient than any other solution posted and it also support fires on regular interval through its onTick() method.

Have a look at this example,

 new CountDownTimer(3000, 1000) { public void onTick(long millisUntilFinished) { // You don't need anything here } public void onFinish() { dialog.dismiss(); } }.start();
1

You can do something like this:

new AsyncTask<Void, Void, Void>
{ ProgressDialog dialog = new ProgressDialog(MainActivity.this); @Override protected void onPreExecute() { super.onPreExecute(); dialog.setTitle("Please wait"); dialog.setMessage("Preparing resources..."); dialog.setCancelable(false); dialog.show(); } @Override protected Void doInBackground(Void... params) { try{ Thread.sleep(3000); } catch(Exception e) { e.printStackTrace(); } } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); if (dialog!=null && dialog.isShowing()) { dialog.dismiss(); } }
}.execute();

Nothing comes between dismiss and show.. the time depending upon you. For example dialog will show before server access and it will dismiss getting result means

 dialog.show(); ServerCall(); dialog.close();

If you need empty delay means then use CountDownTimer call between that..

In case some one looking for Xamarin.Android (using C#) solution (of Peter Knego's answer), here is how:

new Handler().PostDelayed(() => { dialog.dismiss();
}, 1000);

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like