Detect power button long press

前端 未结 11 2291
轮回少年
轮回少年 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条回答
  •  -上瘾入骨i
    2020-11-27 19:04

    The method used above by R. Zagórski worked for me very well for a long time, but from some revision of Android 9 the onCloseSystemDialogs method stopped receiving "globalactions".

    As a workaround, my app is already using Accessibility. From inside the AccessibilityService you can add this code in onAccessibilityEvent

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        Log.i(TAG,"Accessibilityevent");
        if (event == null || event.getPackageName()==null||event.getClassName()==null)
            return;
    
    
        if (event.getClassName().toString().contains("globalactions")){
            //TRIGGER YOUR CODE HERE
    
        }
            ....
    

    Note that were I put the comment "TRIGGER YOUR CODE HERE" I actually just call the same code that was previously in onCloseSystemDialogs.

    Note that so far this is only tested to be working on a Pixel 2 running latest Android. I do not have any other phones running a recent enough version so can't test if the solution is sufficiently generic across phones.

提交回复
热议问题