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

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.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit")
.setMessage("Are you sure you want to leave?")
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which){
// Exit the activity
YourActivity.this.finish();
}
})
.show();

// Say that we've consumed the event
return true;
}

return super.onKeyDown(keyCode, event);
}

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