1

I use this code to listen to volume key button press: https://stackoverflow.com/a/27855766/2977288

But when the user holds the volume button, the listener gets fired again and again.

How can I stop that and only listen once, when the button is clicked and not when the button is press constantly?

jmingrove21
  • 181
  • 1
  • 3
  • 15
Zoker
  • 2,020
  • 5
  • 32
  • 53

2 Answers2

2

Change KeyEvent.ACTION_DOWN for KeyEvent.ACTION_UP, that way it will only fire when you release the button.

See: https://developer.android.com/reference/android/view/KeyEvent

Lucas Cabrales
  • 2,073
  • 1
  • 12
  • 21
0

Try overriding the method that handles long press, something like this:

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) 
    {
        // do what you want to do here
        return true;
    }
    if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) 
    {
        // do what you want to do here
        return true;
    }

    // default action if not handled
    return super.onKeyLongPress(keyCode, event);
}
Ahsan Tarique
  • 581
  • 1
  • 11
  • 22