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
416 views
in Technique[技术] by (71.8m points)

keyevent - Android: Listen for power key press

I am currently trying to listen for when the power button is pressed. Ultimately I would like to have some code run when the power button is pressed twice, to check whether the screen is locked or unlocked. I currently have this:

  @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);//prevent phone from being locked
}

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

    switch (keyCode) {
        case KeyEvent.KEYCODE_POWER:
        {
            Toast.makeText(getBaseContext(), "Power button pressed", Toast.LENGTH_LONG).show();

            return true;
        }
        case KeyEvent.KEYCODE_MENU:
            Toast.makeText(getBaseContext(), "Menu Button Pressed", Toast.LENGTH_LONG).show();

            return true;
    }
    return super.onKeyDown(keyCode, event);
}

The code works fine to toast for the menu keyevent but doesn't do anything for the power key event. Any ideas?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Although I couldn't capture the hardware key I ended up being able guess that the power key was pressed by using a broadcast receiver that listens for whether the screen is turned off or on. I used:

            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                    //do something 
            }

            else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                    //do something else
            }

I was able to be more sure that the power button was being pressed by having a count that would timeout after a couple second. This way I have the user press the power button three times to ensure that proper behavior.


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

...