How to hook into the Power button in Android?

后端 未结 9 1541
挽巷
挽巷 2020-11-22 10:34

On an Android device, where the only buttons are the volume buttons and a power button, I want to make the app react to presses on the power button (long and short). How is

9条回答
  •  忘了有多久
    2020-11-22 11:08

    You could overwrite the public boolean onKeyDown(int keyCode, KeyEvent event) and public boolean onKeyUp(int keyCode, KeyEvent event) functions in your Activity class and test if keyCode is equal to KeyEvent.KEYCODE_POWER.

    I haven't tested this, but I would assume the system treats this like it does the Home key in that you cannot stop the system from receiving the key event, you can only observe that it occurs. To test this, try returning True from the above functions and see if this catches the key event.

提交回复
热议问题