Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

android - Detect two hardware button press simultaneously

I want to add listener when my two hardware button presses like volume button and power button. But i came to know that you can't override power button. Actually i want to take snaps of screen so i came up with this solution. So this is what i wanted to achieve if you have any suggestion about this please share it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your Activity. Try below code for Volume UP + Power key. You can reduce PRESS_INTERVAL to get effect like 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);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...