coderslay
coderslay

Reputation: 14370

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

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?

Upvotes: 10

Views: 11508

Answers (4)

Sniper
Sniper

Reputation: 2452

This will help you

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

Upvotes: 26

Thanasis Kapelonis
Thanasis Kapelonis

Reputation: 1177

There is also

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

which seems to be handling specifically the dismiss event.

Upvotes: 2

Rajeel
Rajeel

Reputation: 384

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);
 }

Upvotes: 1

Altaaf
Altaaf

Reputation: 527

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
        }
});

Upvotes: 0

Related Questions