immagonnagetya
immagonnagetya

Reputation: 101

How to properly override a dispatchKeyEvent in Android

I get

D/InputEventConsistencyVerifier( 2144): KeyEvent: ACTION_UP but key was not down.`
D/InputEventConsistencyVerifier( 2144): in com.android.internal.policy.impl.PhoneWindow$DecorView@41689658

warnings all over when I try to do this in my activity:

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if ((/*some boolean checks*/) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
            /*some custom functions*/
            return true;
        }
    }
    return super.dispatchKeyEvent(event);
}

What is the correct way of overriding dispatchKeyEvent in the activity level? Are these warnings fine? Should I do corresponding changes in the onKeyUp and onKeyDown of my views?

Upvotes: 4

Views: 32913

Answers (2)

Levite
Levite

Reputation: 17617

As ForeverLearning pointed out in the comment is that super.dispatchKeyEvent() is not being called on your handled DOWN events, which is why on the up events it appears to the system to be an up event (your return super.dispatchKeyEvent) before having a down (your return true).

What Pratik Butani might have wanted to say in his code answer is that you could use the KeyEvent.Action_UP instead of the DOWN to get rid of the specific error.

The problem with just calling it as well is that it will be propagaded further down as well (handled by other routines as well / double).

TL;DR: If you want to keep functionality as is, and get rid of the error, consider also NOT calling dispatchKeyEvent on ACTION_UP of the action/situation/i.e. enter press. E.g.

if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {

    // No matter if up or down, we handle this event =>
    // => return true (which gets rid of the OPs error)

    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        /*some custom functions*/
    }

    return true;
}
return super.dispatchKeyEvent(event);

Upvotes: 1

user3355820
user3355820

Reputation: 272

Try this

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
        if (event.getAction() == KeyEvent.ACTION_UP){

         enter();

            return true;
    }}
    return super.dispatchKeyEvent(event);
};

Upvotes: 9

Related Questions