Screen on/off detection

前端 未结 4 1145
遥遥无期
遥遥无期 2021-02-14 02:07

here i am trying to determine whether the screen is on or not but it doesn\'t seems to be working when press power lock/unlock button. Application works with no error but the co

相关标签:
4条回答
  • 2021-02-14 02:11

    Intent.ACTION_SCREEN_OFF and ACTION_SCREEN_ON check out for above broadcasts registration. here you can find a good example.

    0 讨论(0)
  • 2021-02-14 02:12

    Register your BroadcastReceiver in a backgroung Service for Intent.ACTION_SCREEN_ON and Intent.ACTION_SCREEN_OFF events. It worked for me.

    0 讨论(0)
  • 2021-02-14 02:13

    You can try adding this inside your activity.

    IntentFilter filter = new IntentFilter(); 
    filter.addAction(Intent.ACTION_SCREEN_OFF); 
    BroadcastReceiver mReceiver = new ScreenReceiver(); 
    registerReceiver(mReceiver, filter); 
    

    Similarly you can add for ACTION_SCREEN_ON also

    0 讨论(0)
  • 2021-02-14 02:32

    The approach with the ACTION_SCREEN did not work for me. After some different solutions this code finally solved the problem for me:

    /**
     * Is the screen of the device on.
     * @param context the context
     * @return true when (at least one) screen is on
     */
    public boolean isScreenOn(Context context) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
            boolean screenOn = false;
            for (Display display : dm.getDisplays()) {
                if (display.getState() != Display.STATE_OFF) {
                    screenOn = true;
                }
            }
            return screenOn;
        } else {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            //noinspection deprecation
            return pm.isScreenOn();
        }
    }
    
    0 讨论(0)
提交回复
热议问题