Search code examples
androidandroid-alertdialogandroid-dialog

Alert dialog not dismiss when application goes background in Android


I used the following code:

Alertdialog alertDialog =null;
AlertDialog.Builder builder=new Builder(this);
        builder.setTitle(title);
        builder.setMessage(message);

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {

            }
        });
        alertDialog=builder.create();
        builder.create().show();

When I click home key(without any user event in "OK" button) I dismiss the alert dialog using the following code:

@Override
    protected void onPause() {

            if(alertDialog != null){
               alertDialog.dismiss();
            }

        }

        super.onPause();
    }

When re launch the application the alert dialog won't disappear.

What I did wrong?


Solution

  • The problem is that you created two AlertDialog instances here:

    alertDialog=builder.create();
    builder.create().show();
    

    Then you called dismiss() on the dialog that is not actually shown. This should fix the problem:

    alertDialog=builder.show();