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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With