Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : Add delay to Alert Dialog

I am in a situation where i need an alert dialog to pop up after some seconds. I tried Handler with postDelayed(), it didn't work.

new Handler().postDelayed(new
Runnable() {
        @Override
        public void run() {
          AlertDialog.Builder builder = new     AlertDialog.Builder(
                        MyActivity.this);
                builder.setTitle("My title...    ");
                builder.    setMessage("my msg..");
                builder.     setPositiveButton("OK",
                         new     DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                int     which) {
                            Log.    e("info", "OK");
                            }
                        });

                builder.show();
        }
    });
        }
}, 33000); 
like image 593
Emm Jay Avatar asked Mar 21 '23 05:03

Emm Jay


1 Answers

You have to add this piece of code below builder.show(); It works for me.

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
        dialog.dismiss();
    }   
}, 1500);  // 1500 seconds

Edit:

I use this in a different way that I could see in your case. Here you can see my complete code. In my case I only want that apears a "simulate" Progress Dialog, and after some time it disappears.

protected void ActiveProgressDialog() {
    final ProgressDialog dialog = ProgressDialog.show(getActivity(), "", getResources().getString(R.string.carregantInfo), true);
    dialog.show();
    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            dialog.dismiss();
        }   
    }, 1500);  // 1500 milliseconds
}

}
like image 143
Joan Gil Avatar answered Mar 30 '23 10:03

Joan Gil