3

I'm confused about the usage of onKeyDown() and onBackPressed(). Are both of these overriding methods the same in functionality & usage? If not so, then what's the correct usage for both?

You might be referring to this question here, which asks for place of implementation, but I'm asking for why and when rather then where.

wazz
  • 4,953
  • 5
  • 20
  • 34
Muahmmad Tayyib
  • 689
  • 11
  • 28

1 Answers1

12

onKeyDown() can be used for any hardware key on your Android device, that can be the power button, back button, or volume button.

onBackPressed() is only called when the back button is pressed.

Here are the differences:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // back was pressed
        return true;
    } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
      // volume up was pressed
    }
    return super.onKeyDown(keyCode, event);
}

@Override
public void onBackPressed() {
    // back was pressed
}

See a full list of KeyCodes here:

https://developer.android.com/reference/android/view/KeyEvent.html

As you can see, it's easier to implement onBackPressed() if you want to detect a back press.

gi097
  • 7,313
  • 3
  • 27
  • 49