Trigger an event by pressing the 2x volume button?

2

I would like to trigger an event only by pressing the 2x volume button quickly.

I have the following code, but it fires when I press the button once. How do I trigger it only by pressing 2 times at a certain speed?

Follow the code:

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    int action = event.getAction();
    int keyCode = event.getKeyCode();
    switch (keyCode) {
        case KeyEvent.KEYCODE_VOLUME_UP:
            if (action == KeyEvent.ACTION_UP) {
                toDoUp();
            }
            return true;
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            if (action == KeyEvent.ACTION_DOWN) {
                toDoDown();
            }
            return true;
        default:
            return super.dispatchKeyEvent(event);
    }
}
    
asked by anonymous 13.06.2017 / 15:01

1 answer

0

Functional example below, modify it to suit your needs:

KeyPressTool:

public class KeyPressTool {

private static int doublePressSpeed = 300; // double keypressed in ms
private static long timeKeyDown = 0;       // last keyperessed time
public static int lastKeyPressedCode;

public static  boolean isDoublePress(KeyEvent ke) {
    if ((ke.getWhen() - timeKeyDown) < doublePressSpeed) {
        return true;
    } else {
        timeKeyDown = ke.getWhen();
    }
    lastKeyPressedCode = ke.getKeyCode();
    return false;
}
}

// Testing

f (KeyPressTool.isDoublePress(ke) && KeyPressTool.lastKeyPressedCode == ke.getKeyCode()) {
System.out.println("double pressed " + ke.getKeyText(ke.getKeyCode());
}
    
13.06.2017 / 16:30