Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 807
immagonnagetya Avatar asked Oct 22 '25 22:10

immagonnagetya


2 Answers

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);
};
like image 86
user3355820 Avatar answered Oct 25 '25 11:10

user3355820


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);
like image 43
Levite Avatar answered Oct 25 '25 12:10

Levite



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!