Detect power button long press

前端 未结 11 2331
轮回少年
轮回少年 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:09

    You can catch the power button event by overriding onKeyDown method

    @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
                Log.e("key","long");
                /*//disable the system dialog
                Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
                sendBroadcast(closeDialog);*/
                Toast.makeText(getApplicationContext(),"Power",Toast.LENGTH_SHORT).show();
            }
            return super.onKeyDown(keyCode, event);
        }
    

    As my knowledge we can't do this outside activity (such as background service)

提交回复
热议问题