Android: Listen for power key press

孤街浪徒 提交于 2019-11-27 14:33:17

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.

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

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
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!