如何捕获Longpress并在KEYCODE_VOLUME_UP上调用标准操作?

时间:2013-02-19 13:26:59

标签: android volume key-events

我希望用户能够长按volumeUp硬件按钮以跳过歌曲,并在短按时执行常规的volumeUp操作。

我能够区分两者(我发现this solution,使用onKeyDown,onKeyLongPress和onKeyUp之间的标志)但是我想知道我是否还可以在音量调高按钮时调用标准/超级动作被压了。 我似乎无法弄清楚何时调用volumeUp动作(在onKeyDown-或onKeyUp-event中)以及在哪里调用它。

或者我应该编写自己的功能来改变音量?

感谢。

我的代码:

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

1 个答案:

答案 0 :(得分:3)

看看也许这会帮助你。

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