Simultaneous detection of two hardware buttons

I want to add a listener when my second hardware button is pressing the volume button and the power button. But I found out that you cannot cancel the power button. Actually I want to take screenshots, so I came up with this solution. So this is what I wanted to achieve, if you have any suggestions on this, please share it.

+3


source to share


2 answers


You need to override the onKeyDown and onKeyUp events to detect two pressed buttons.



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

      

+2


source


In your activity. Try entering the code for the UP + Power key. You can decrease PRESS_INTERVAL to get the effect, since both buttons are pressed at the same time. Hope this helps!



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

      

+2


source







All Articles