Android: Listen for power key press
Asked Answered
D

3

3

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?

Debate answered 7/10, 2011 at 0:42 Comment(1)
There is no API for this but you can achieve it using reflection. https://mcmap.net/q/82478/-how-to-capture-app-switch-key-using-onkeydown-in-androidBruce
D
8

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.

Debate answered 18/1, 2012 at 15:20 Comment(2)
hey, AFAIK, this intent is broadcasted after the event has occurred, is it what you want ?Belmonte
This intent is broadcasted ~ a second or two later, has someone experienced this?Nye
M
2

AFAIK, it's not possible for Power key.

You might want to refer to this answer: http://groups.google.com/group/android-developers/browse_thread/thread/a4db4def1bdaa8d9

Membranous answered 7/10, 2011 at 2:2 Comment(0)
C
0

I've used android-annotations "@Receiver" annotation.

Add this to your "@EActivity" annotated Activity:

@Receiver(actions = Intent.ACTION_SCREEN_OFF)
protected void onPowerButtonPressed() {
// add your code
}
Carline answered 24/6, 2016 at 12:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.