Home » Android » How to capture an event when a user dismiss an alert dialog by pressing the backKey in Android

How to capture an event when a user dismiss an alert dialog by pressing the backKey in Android

Posted by: admin May 14, 2020 Leave a comment

Questions:

I need to catch an event when the user presses the back key and try to dismiss the dialog
I have a code like this

AlertDialog alertDialog = new AlertDialog.Builder(AppNotification.this).create();
    alertDialog.setTitle("Caution");
    alertDialog.setMessage("Alert");
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
        finish();
    } });
    alertDialog.show();
}

Now here i have given the user an option,But suppose if he presses the back key then i need to perform some other action.how to do it?

How to&Answers:

This will help you

alertDialog.setOnCancelListener(new OnCancelListener() {
    public void onCancel(DialogInterface dialog) {
        // Your code ...                
    }
});

Answer:

There is also

alertDialog.setOnDismissListener(dialog -> { /* code goes here */ });

which seems to be handling specifically the dismiss event.

Answer:

You can capture the back key event
when your alert appears set some boolean to true

AlertDialog alertDialog = new AlertDialog.Builder(AppNotification.this).create();
    alertDialog.setTitle("Caution");
    alertDialog.setMessage("Alert");
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
        finish();
    } });
  isAlertShowing = true;   // set to true for alert
    alertDialog.show();
}

then in event

@Override
 public boolean onKeyDown(int keyCode, KeyEvent event)
 {
  if (keyCode == KeyEvent.KEYCODE_BACK) 
        {
            if(isAlertShowing)
            {
               // perform your task here
             }

        }

        return super.onKeyDown(keyCode, event);
 }

Answer:

Create a button for managing the back key event. Now inside the onClick event try to provide the below given code.

back_key.setOnClickListener(new OnClickListener() 
{

        public void onClick(View v) 
        {
             // Your Tracking Code
        }
});