Matt McMinn
Matt McMinn

Reputation: 16291

onKeyDown not always called in Android app

I've created a simple android game, based on the Lunar Lander sample, and I'm having a problem with handling key events. When the activity starts, the only keys that onKeyDown or onKeyUp get called for are the dpad up/down/left/right keys. Neither the menu, back, or dpad_center keys trigger onKey methods. However, once I've pushed one of the dpad up/down/left/right buttons, pressing the menu, back, or dpad_center keys do trigger these methods. I'm not getting any errors, or any indication of what's going wrong.

It's possible that the focus is set wrong - the activity is started from a button on screen, so it could be in touchscreen mode. If that's the case, shouldn't touching the back button get me in to the right focus mode so that I can catch the event?

I'm using the emulator from SDK-1.5r3. I have not been able to try this on a real phone yet. Here's my onKeyDown.

public boolean onKeyDown(int keyCode, KeyEvent msg)
{
    Log.d(TAG, "onKeyDown: " + keyCode);
    return super.onKeyDown(keyCode, msg);
}

Thanks

Matt

Upvotes: 19

Views: 26635

Answers (3)

Anas Lakhani
Anas Lakhani

Reputation: 87

insert this code

getWindow().getDecorView().setFocusable(true);
        if (SDK_INT >= Build.VERSION_CODES.O) {
            getWindow().getDecorView().setFocusedByDefault(true);
        }

Upvotes: 0

yuliskov
yuliskov

Reputation: 1498

Activity's onKeyDown/onKeyUp methods not always called. Unlike them dispatchKeyEvent on Activity fired always. Move keydown/keyup logic here. Works well.

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        // keydown logic
        return true;
    }
    return false;
}

Upvotes: 23

haseman
haseman

Reputation: 11313

Is this onKeyDown in a view or in the activity?

If setContentView is called passing in a view, and that view has setFocusable(true) called on it, all key events will bypass the activity and go straight into the view.

On the other hand, if your onKeyDown is in the view, and you haven't called setContentView on the Activity and setFocusable(true) on the view, then your Activity will get the key events and not the View.

Look for those specific calls but I think you're right about it being a focus issue.

Upvotes: 37

Related Questions