Not able to catch android back button event

coder picture coder · Nov 16, 2011 · Viewed 11.5k times · Source

I am trying to catch the back button event for Android. I know there is a lot about this already on the forms, however, my code does not work as the examples given. Here is my code snippet to capture the event:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
    if(keyCode == KeyEvent.KEYCODE_BACK){
        Log.d(TAG, "back key captured");
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

I also tried this:

@Override
public void onBackPressed(){
    Log.d(TAG, "in onBackPressed");
    finish();
}

The output from LogCat that either event got fired doesn't show up. Anyone know a possible reason for this?

Thanks.

Answer

Brian picture Brian · Nov 16, 2011

Another method to is to override the public void onBackPressed() method. It's more straightforward and easier to do.