Android 判断当前是否亮灭屏状态或黑屏锁屏状态-}

引用方法:

public static boolean isScreenOn(Context context) {
       PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        return pm.isScreenOn();
    }

 

如果isScreenOn 为true,则表示屏幕“亮”了。
屏幕“亮”,表示有两种状态:a、未锁屏亮屏 b、目前正处于解锁状态亮屏 。这两种状态屏幕都是亮的 
屏幕“暗”,表示目前屏幕是黑的 

2.通过KeyguardManager的inKeyguardRestrictedInputMode方法,判断当前是否黑屏及锁屏的情况:

KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
boolean flag = mKeyguardManager.inKeyguardRestrictedInputMode();

引用方法:

public static boolean isScreenOff(Context context) {
        KeyguardManager manager = (KeyguardManager) context.getSystemService(context.KEYGUARD_SERVICE);
        return manager.inKeyguardRestrictedInputMode();
    }

如果flag为true,表示有两种状态:a、屏幕是黑的(锁屏中黑的) b、目前正处于解锁状态(锁屏中但是亮的) 。
如果flag为false,表示目前未锁屏  (亮的)

3.可以通过反射机制来调用

private static Method mScreenState;
try {
    mScreenState = PowerManager.class.getMethod(isScreenOn, new Class[] {});
    PowerManager pm = (PowerManager) context.getSystemService(Activity.POWER_SERVICE);
    boolean isScreenOn= (Boolean) mScreenState.invoke(pm);
} catch (Exception e) {
    e.printStackTrace()
}

 

 4,特殊广播方法:

private ScreenBroadcastReceiver mScreenReceiver;
private class ScreenBroadcastReceiver extends BroadcastReceiver {
    private String action = null;
 
 
    @Override
    public void onReceive(Context context, Intent intent) {
        action = intent.getAction();
        if (Intent.ACTION_SCREEN_ON.equals(action)) {           
            // 开屏,处理什么逻辑
        } else if (Intent.ACTION_SCREEN_OFF.equals(action)) { 
            // 锁屏
        } else if (Intent.ACTION_USER_PRESENT.equals(action)) { 
            // 解锁
        }
    }
}
private void startScreenBroadcastReceiver() {
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_USER_PRESENT);
    context.registerReceiver(mScreenReceiver, filter);
}

上一篇:【LeetCode】【算法】581. 最短无序连续子数组-解题思路


下一篇:vue2 - el-table表格设置动态修改表头