Search This Blog

Sunday 3 June 2012

Show an Alert Message when user press the back button

This post is explaining how to show a alert message box when the user clicks the back button of the phone.

@Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("Application TiTle");
                builder.setMessage("Back Button Pressed");
                AlertDialog alert = builder.create();
                alert.show();
            }
     
            return true;

        }

Add a onKeyDown Method to the activity class and handle the keycode (KEYCODE_BACK).

This will receive when ever the activity is in front and user pressed a back button of phone.

You can create a simple alert message using the AlertDialog interface.

1 comment:

  1. Nice snippet.
    I have also another solution to display alert on back pressed. I write an article on same. Please visit http://www.chintanrathod.com/display-alert-on-back-button-pressed-in-android-studio/

    ReplyDelete