How to catch Longpress and call the standard action on KEYCODE_VOLUME_UP?

一世执手 提交于 2020-01-15 11:42:28

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/14958701/how-to-catch-longpress-and-call-the-standard-action-on-keycode-volume-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!