Android - Volume Buttons used in my application

The next would be better because a long click for KeyEvent.KEYCODE_VOLUME_UP does not work right in the previous answer.

@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);
    }
}

You need to capture all actions:

@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);
        }
    }

Just to complete the previous answers, if you want long click support you should check how long the key was down using:

event.getEventTime() - event.getDownTime() > ViewConfiguration.getLongPressTimeout() 

In the end the code will look like this:

    @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) {
                if (event.getEventTime() - event.getDownTime() > ViewConfiguration.getLongPressTimeout()) {
                    //TODO long click action
                } else {
                    //TODO click action
                }
            }
            return true;
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            if (action == KeyEvent.ACTION_UP) {
                if (event.getEventTime() - event.getDownTime() > ViewConfiguration.getLongPressTimeout()) {
                    //TODO long click action
                } else {
                    //TODO click action
                }
            }
            return true;
        default:
            return super.dispatchKeyEvent(event);
    }
}

Tags:

Android