Intercepting the back button Intercepting the back button android android

Intercepting the back button


In an activity you can just override

onBackPressed()

edit: that is api lvl 5+ :/ for 4 and below you gotta override onKeyDown()


Simply override the onKeyDown(int, KeyEvent) method in your activity and look for the back button. Return true so that the event is consumed.

public boolean onKeyDown(int keyCode, KeyEvent event) {    if (keyCode == KeyEvent.KEYCODE_BACK) {        //Do something here        return true;    }    return super.onKeyDown(keyCode, event);}


As schwiz pointed out, you'll want to override the onBackPressed() method in your activity class (http://developer.android.com/reference/android/app/Activity.html#onBackPressed()).

I just wanted to add that if you did want to at some stage continue with or access the standard the back operation (after say, displaying a dialog), then you simply call super.onBackPressed() or ActivityName.super.onBackPressed() from anywhere in the Activity.