Android How to listen for Volume Button events?

Solution 1:

I don't know if you can get long press events for the hardware keys.

I've used this code to listen for the volume button before.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
        // Do something
    }
    return true;
}

If that doesn't work for you let us know what device you are testing on.

Kotlin

override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { 
        // Do something
    }
    return true
}

Solution 2:

Another approach

@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_DOWN) {
                //TODO
            }
            return true;
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            if (action == KeyEvent.ACTION_DOWN) {
                //TODO
            }
            return true;
        default:
            return super.dispatchKeyEvent(event);
        }
    }

Solution 3:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
        // ... your code
        return true;
    } else if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)) {
        // ... your code
        return true;
    } else
        return super.onKeyDown(keyCode, event);
}