Android: Listen for power key press

前端 未结 3 774
一生所求
一生所求 2020-12-03 13:20

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

相关标签:
3条回答
  • 2020-12-03 13:24

    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
    }
    
    0 讨论(0)
  • 2020-12-03 13:45

    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

    0 讨论(0)
  • 2020-12-03 13:47

    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.

    0 讨论(0)
提交回复
热议问题