我有锁屏问题。有时,当我睡觉时,然后在唤醒手机后,会立即调用onResume,然后调用onPause,这会使我的应用程序混乱。我以为我可以采取一种解决方法,如果显示了锁屏,则忽略onPause中的逻辑,但是我不知道如何检查它。我尝试使用PowerManger和KeyguardManager(如建议的here)使用,但没有用。我还尝试检查onPause中的 Activity hasWindowFocus(),但即使显示锁屏也返回true。有什么办法可以知道当前是否显示锁屏?

最佳答案

如果您的屏幕已锁定,则选中此选项将返回true。

/**
 * Returns true if the device is locked or screen turned off (in case password not set)
 */
public static boolean isDeviceLocked(Context context) {
    boolean isLocked = false;

    // First we check the locked state
    KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
    boolean inKeyguardRestrictedInputMode = keyguardManager.inKeyguardRestrictedInputMode();

    if (inKeyguardRestrictedInputMode) {
        isLocked = true;

    } else {
        // If password is not set in the settings, the inKeyguardRestrictedInputMode() returns false,
        // so we need to check if screen on for this case

        PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            isLocked = !powerManager.isInteractive();
        } else {
            //noinspection deprecation
            isLocked = !powerManager.isScreenOn();
        }
    }

    Loggi.d(String.format("Now device is %s.", isLocked ? "locked" : "unlocked"));
    return isLocked;
}

10-08 17:56