Detect power button long press

前端 未结 11 2337
轮回少年
轮回少年 2020-11-27 18:38

I\'ve been reading some posts here on Stackoverflow, and I didn\'t find a good solution, I\'m wondering if it\'s possible to detect when the user long press the power button

11条回答
  •  我在风中等你
    2020-11-27 19:13

    This simple solution works:

        @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int keyPressed = event.getKeyCode();
        if(keyPressed==KeyEvent.KEYCODE_POWER){
            Log.d("###","Power button long click");
            Toast.makeText(MainActivity.this, "Clicked: "+keyPressed, Toast.LENGTH_SHORT).show();
            return true;}
        else
            return super.dispatchKeyEvent(event);
    }
    

    If you want to stop system pop-up, use the onWindowFocusChangedmethod specified in one of the answers below.

    The output will show the toast with "Clicked:26" as attached below.

提交回复
热议问题