Android onKeyLongPress


Ask by : v1r0x November 09, 2012 18:17

I'm working on an android music player and want to skip tracks using long press volume keys. I've found some implementations, but none of them worked as I want it. I want to skip song on long press and change volume on short press (normal behavior). In all tutorials/answers they handled long press with onKeyDown and onKeyLongPress but the short/normal press was only logged in onKeyUp.

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    Log.d(TAG, "long pressed");
    switch(keyCode){
    case KeyEvent.KEYCODE_VOLUME_UP:
        songNumber++;
        playSong(songs.get(songNumber));
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        songNumber--;
        playSong(songs.get(songNumber));
        return true;
    }
    return super.onKeyLongPress(keyCode, event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch(keyCode){
    case KeyEvent.KEYCODE_VOLUME_UP:
        event.startTracking();
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        event.startTracking();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    switch(keyCode){
    case KeyEvent.KEYCODE_VOLUME_UP:
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        return true;
    }
    return super.onKeyUp(keyCode, event);
}

This is my code but with this I can only skip songs and short press has no effect. So I have only one volume level :(

I have no idea what to try now. Help is appreciated. Thanks!

-v1r0x

View original question

Answer by : v1r0xNovember 09, 2012 18:17

Ok, I have found a solution. Not the best, but it works. OnKeyDown and OnKeyLongPress are still the same, but OnKeyUp is now this:

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if(!event.isCanceled()){
        switch(keyCode){
        case KeyEvent.KEYCODE_VOLUME_UP:
            audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
            break;
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
            break;
        }
    }
    return super.onKeyUp(keyCode, event);
}
View original answer