How to hook into the Power button in Android?

后端 未结 9 1622
挽巷
挽巷 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条回答
  •  旧时难觅i
    2020-11-22 11:22

    On you activity add:

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
            // do what you want with the power button
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    

    Though... this kind of keys are somehow special... not sure if it can give problems to you.

提交回复
热议问题