onBackPressed doesn't work with AlertDialog

easy peeasy..

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("BROADCAST")
        .setMessage(text)
        .setCancelable(true)
        .setPositiveButton("Dismiss",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        finish();
                    }
                })
        .setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog) {
                                    finish();
                                }
                            });
AlertDialog alert = builder.create();
alert.setCanceledOnTouchOutside(false);
alert.show();

For answer in Kotlin see here:Not working onbackpressed when setcancelable of alertdialog is false


you can set a key listener

builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

                    if(keyCode == KeyEvent.KEYCODE_BACK){
                        dialog.dismiss(); // dismiss the dialog
                       YourActivity.this.finish(); // exits the activity

                    }

                    return true;
                }
            })