Search code examples
androidbuttonvolume

How to detect volume up and down long pressed together?


How to check if both volume up and volume down buttons are pressed together for few seconds in Android device ?

And if pressed, I need to call a function. This detection should work if my application is installed in any android device. Any near solution will also do.


Solution

  • You need to detect when the both of the keys are pressed using onKeyDown callback, something like should work:

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