同时检测两个硬件按钮

时间:2014-08-21 07:18:00

标签: android

当我的两个硬件按钮按下音量按钮和电源按钮时,我想添加监听器。但我知道你无法覆盖电源按钮。实际上我想拍摄屏幕快照,所以我想出了这个解决方案。所以这就是我想要实现的,如果您对此有任何建议请分享。

2 个答案:

答案 0 :(得分:3)

在您的活动中。尝试下面的Volume UP + Power键代码。您可以减少PRESS_INTERVAL以获得效果,就像同时按下两个按钮一样。希望这有助于!

private static final int PRESS_INTERVAL = 700;
private long mUpKeyEventTime = 0;
public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_POWER == event.getKeyCode()) {            
            if ((event.getEventTime() - mUpKeyEventTime) < PRESS_INTERVAL) {
                // This is to check if Volume UP key and Power key are pressed at the same time.
                // Do the Task. Here You can add logic to take screenshot
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(KeyEvent.KEYCODE_VOLUME_UP == keyCode){
            mUpKeyEventTime = event.getEventTime();
        }
        return super.onKeyUp(keyCode, event);
    }

答案 1 :(得分:2)

您需要覆盖onKeyDownonKeyUp事件才能检测到按下的两个按钮。

 public boolean first,second;

 public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_POWER){
        first = true;
    }
    else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
        second = true;
    }

    if(first && second) {
        // Two buttons pressed, Do your stuff
    }
    return true;
 }

 public boolean onKeyUp(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_POWER){
        first = false;
    }
    else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
        second = false;
    }
    return true;
 }