1

I want the users to be able to longpress the volumeUp hardware button for skipping a song, and do the regular volumeUp action on a short press.

I'm able to differentiate between both (I found this solution, working with flags between onKeyDown, onKeyLongPress and onKeyUp) but I'm wondering if I can still call the standard/super action when the volume up button has been pressed. I can't seem to figure out when the volumeUp action is being called (in the onKeyDown- or onKeyUp-event) and where to call it.

Or should I just write my own function to change the volume?

Thanks.

My code:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
        event.startTracking();
        if (bLong) {
            bShort = false;
            return true;
        } else {

            bShort = true;
            bLong = false;

            return true;
        }
    }

    return super.onKeyDown(keyCode, event);
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
        if (bShort) {
            bShort = false;
            bLong = false;
            if (mp != null) {
                //HERE IS WHERE I WANT TO CALL THE VOLUME-UP ACTION
            }
            return true;
        }
    }
    return super.onKeyUp(keyCode, event);
}

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
        if (bRunning && mp != null) {
            playNextSong();
        }
        bShort = false;
        bLong = false;
        return true;
    }
    return super.onKeyLongPress(keyCode, event);
}
Community
  • 1
  • 1
tofkop
  • 13
  • 1
  • 4
  • Have you solved? I'm trying to develop an app to skip tracks with volume buttons too.. Can you help me? – Atlas91 Jul 24 '14 at 14:47

1 Answers1

3

Take a look maybe this gonna help you.

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 && event.isLongPress()) {
            //(skipping a song)
            }
            if (action == KeyEvent.ACTION_UP) {           
            //(vol up)
            }
            return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        if (action == KeyEvent.ACTION_UP)

        return true;
    default:
        return super.dispatchKeyEvent(event);
    }
}
Guilherme Gregores
  • 1,050
  • 2
  • 10
  • 27
  • Fantastic, didn't even need that much, just needed to catch "if (action == KeyEvent.ACTION_DOWN && event.isLongPress())" and return true in that case. The volume up is handled by the super.dispatchKeyEvent(event). And I can clean up a big chunk of my messy code! Thanks! – tofkop Feb 19 '13 at 14:24
  • I'm glad to have helped ^^ – Guilherme Gregores Feb 19 '13 at 14:36