9

I'm trying to get my app to react to a long key press on volume down with the following code:

public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
        Log.w("myApp", "LONG PRESS");
    }
    return super.onKeyLongPress(keyCode, event);
}

However, it only spams a bunch of onKeyPress() events for volume down, and onKeyLongPress() never gets called. My intention is to leave the volume down and up "short" presses alone, and have my app react differently to the volume long press.
Can anybody point out what I'm missing?

Marcus
  • 5,407
  • 3
  • 31
  • 54

1 Answers1

21

You are almost there. You need to detect the same key event in the onKeyPress handler and start tracking it so that the long press can work. Here's the code you need:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
        event.startTracking();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
Jeff B
  • 8,572
  • 17
  • 61
  • 140
Craig B
  • 4,763
  • 1
  • 25
  • 19
  • Any idea how I can catch this key event from going on further to Android Volume Manager and changing the audio? – Radu Nov 06 '12 at 10:11
  • 1
    @Radu: not tested but: what about "return true;" in your long press callback? Should prevent propagation. But again, not sure this can really work or not. – Benjamin Piette Sep 05 '13 at 13:00