Trigger an event by pressing the 2x volume button?

Asked

Viewed 115 times

2

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

I have the following code, but it fires by pressing the button only once. How to make it fire only if pressed 2 times at a certain speed?

Follows 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);
    }
}
  • This is possible but the first click will be passed to the system. It serves as such?

  • That is the volume indicator will open. If it fits like this I give an answer.

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());
}
  • What method is this getWhen()?

  • Returns the timestamp of when this event occurred.

  • I can’t find you in the Keyevent class.

  • This getWhen() method was created by you, correct?

  • https://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionEvent.html#getWhen()

  • I know it’s not cool to post a link, only this way you’ll understand better...

  • I couldn’t find it in the Keyevent class either

  • In these situations there is no harm passing links. The Android Keyevent class is different and does not have this method.

  • I may have been mistaken, as I’m at work I had no way to test, so when I arrive I’ll take a look.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.