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 KeyCode
s 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.