10

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?

coderslay
  • 13,960
  • 31
  • 73
  • 121
  • [Here][1] is a similar question with an accepted answer. [1]: http://stackoverflow.com/questions/2000102/android-override-back-button-to-act-like-home-button – rics Feb 15 '12 at 07:39
  • Nope.. I am talking about alert dialog and back key event... i know about the BackKeyEvent.... – coderslay Feb 15 '12 at 07:42
  • It was a hint how to override the back button. Rajeel explains how to add it to alert. – rics Feb 15 '12 at 07:54
  • Yup Rajeel way will accomplish what i need to do.. Still i was looking for some better performance ways :) – coderslay Feb 15 '12 at 07:55

4 Answers4

26

This will help you

alertDialog.setOnCancelListener(new OnCancelListener() {
    public void onCancel(DialogInterface dialog) {
        // Your code ...                
    }
});
Paul Chu
  • 1,249
  • 3
  • 19
  • 27
Sniper
  • 2,412
  • 11
  • 44
  • 49
2

There is also

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

which seems to be handling specifically the dismiss event.

1

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);
 }
Rajeel
  • 384
  • 2
  • 7
0

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
        }
});
Altaaf
  • 527
  • 3
  • 11