Android: Capture the BACK button keypress and display a confirmation dialog

0 Comments

An often useful feature to have is the "Are you sure you wish to exit?" confirmation as someone may accidently touch the back button and exit your application.

To add that, we need to first override onKeyDown() in the application and detect the BACK button keypress.

01.@Override
02.public boolean onKeyDown(int keyCode, KeyEvent event) {
03.  //Handle the back button
04.  if (keyCode == KeyEvent.KEYCODE_BACK) {
05.    //Ask the user if they want to quit
06.    new AlertDialog.Builder(this)
07.      .setIcon(android.R.drawable.ic_dialog_alert)
08.      .setTitle("Exit")
09.      .setMessage("Are you sure you want to leave?")
10.      .setNegativeButton(android.R.string.cancel, null)
11.      .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
12.        @Override
13.        public void onClick(DialogInterface dialog, int which){
14.          // Exit the activity
15.          YourActivity.this.finish();
16.        }
17.      })
18.      .show();
19. 
20.    // Say that we've consumed the event
21.    return true;
22.  }
23. 
24.  return super.onKeyDown(keyCode, event);
25.}

A word of warning, in Android 2.0 there is a handler purely for the back button called onBackPressed().

[ Source, Docs, onBackPressed() ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog