Home » Android » Handling Android hardware Back button

Handling Android hardware Back button

Posted by: admin June 15, 2020 Leave a comment


I have an onKeyDown event which is only needed for handling the Up and Down hardware keys in my app. For these it returns true, as they are handled.
For anything else it returns false which I understand means that the OS should handle them.
However, when I press the Back button, my onKeyDown is called and returns false, but there is no other effect. I want/would expect the OS to finish the current Activity and resume the previous one.

Is this correct behavior, or is there something amis?


Cheers guys, my onKeyDown routine looks like this, now I’ve followed CommonsWare’s advice:

public boolean onKeyDown(int keyCode, KeyEvent event) {
    super.onKeyDown(keyCode, event);

    boolean handled = true;

    // handle key presses
    switch (keyCode) {

    case KeyEvent.KEYCODE_DPAD_LEFT:
        mCursorX = mCursorX - 1;
        if (mCursorX < MAP_MIN_X) { mCursorX = MAP_MIN_X; }

    case KeyEvent.KEYCODE_DPAD_RIGHT:
        mCursorX = mCursorX + 1;
        if (mCursorX > MAP_MAX_X) { mCursorX = MAP_MAX_X; }

        handled = false;

    if (handled) {
        return true;

    return super.onKeyDown(keyCode,event);

My class looks like:

public class Map extends Activity implements OnClickListener, SurfaceHolder.Callback, OnTouchListener {

I must admit I didn’t know why the @override and the first ‘super’ line were there, they were just in all the routines I looked at.
If the super.onKeyDown runs the onKeyDown for the Activity, then I probably don’t want it at the start, only at the end if my routine doesn’t handle it, which I think is what I’ve added.
Does that sound about right, or am I still confused?


How to&Answers:

I would recommend chaining to the superclass. In other words, instead of:





You can override the onBackPressed() method, it will be called when the activity has detected the user’s press of the back key. In this case, you don’t need to use the onKeyDown method.


Also, you’re calling super.onKeyDown() twice: once at the beginning of the function and once at the end. You should only need the one at the end.