如何检测音量上下长按?

How to detect volume up and down long pressed together?

如何检查 Android 设备中音量增大和音量减小按钮是否同时按下几秒钟?

如果按下,我需要调用一个函数。如果我的应用程序安装在任何 android 设备中,此检测应该有效。任何接近的解决方案也可以。

您需要使用 onKeyDown 回调来检测何时按下两个键,类似的东西应该可以工作:

public boolean up,down;

public boolean onKeyDown(int keyCode, KeyEvent event) {
   if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
      down = true;
   } else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
      up = true;
   }
   if(up && down) {
    // Two buttons pressed, call your function
   }
   return true;
}

public boolean onKeyUp(int keyCode, KeyEvent event) {
  if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
    down = false;
  } else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
    up = false;
  }
  return true;
}

您需要覆盖一些方法并在那里应用您的逻辑:例如,创建以下变量

private static final int PRESS_INTERVAL = 1000;
private long upKeyTime = 0;

覆盖以下

 @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_VOLUME_DOWN == event.getKeyCode()) {
            if ((event.getEventTime() - upKeyTime) < PRESS_INTERVAL) {
                Toast.makeText(this, "Pressed together", Toast.LENGTH_SHORT).show();
            }
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


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

如果用户在 1 秒内按音量调低键后按音量调低键,此代码将打印 toast。我希望您可以将此代码更改为上下组合键,因为这是上下组合。

public static final int VOLUME_PRESSED__INTERVAL = 100;
private long upKeyEventTime = 0;
private long downKeyEventTime = 0;

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            downKeyEventTime = event.getEventTime();
        } else {
            upKeyEventTime = event.getEventTime();
        }
        if (Math.abs(upKeyEventTime - downKeyEventTime)<= VOLUME_PRESSED__INTERVAL){
            //TODO call your method
            return false;
        }
    }

    return super.onKeyDown(keyCode, event);
}

如果你想要更准确,你可以设置VOLUME_PRESSED__INTERVAL = 0;