1

我正在开发一个 android 音乐播放器,并想使用长按音量键跳过曲目。我找到了一些实现,但它们都没有像我想要的那样工作。我想在长按时跳过歌曲并在短按时更改音量(正常行为)。在所有教程/答案中,他们处理长按,onKeyDownonKeyLongPress短按/正常按仅登录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);
}

这是我的代码,但我只能跳过歌曲,短按无效。所以我只有一个音量级别:(

我不知道现在该尝试什么。帮助表示赞赏。谢谢!

-v1r0x

4

1 回答 1

1

好的,我找到了解决方案。不是最好的,但它有效。 仍然是一样的,但OnKeyDown现在是这样的:OnKeyLongPressOnKeyUp

@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);
}
于 2012-11-09T18:17:32.903 回答