Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between onKeyDown() and onBackPressed()

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.

like image 612
Muahmmad Tayyib Avatar asked Apr 21 '26 23:04

Muahmmad Tayyib


1 Answers

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.

like image 104
gi097 Avatar answered Apr 24 '26 11:04

gi097



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!