检查当前是否显示锁屏

问题描述 投票:0回答:1

我有一个锁屏的问题。有时当我睡觉时,当我唤醒手机后,立即调用onResume,然后调用onPause,这就把我的应用搞乱了。我想,我可以做一个变通的方法,如果锁屏显示,那么忽略我在onPause中的逻辑,但我不知道如何检查它。我尝试使用PowerManger和KeyguardManager,就像建议的那样。此处 但它没有工作,我也尝试在onPause中检查活动是否有WindowFocus(),但即使锁屏显示,它也会返回true。我还尝试在onPause中检查activity是否有WindowFocus(),但即使锁屏显示,它也会返回true。有什么方法可以知道锁屏是否正在显示?

java android kotlin android-lifecycle
1个回答
0
投票

检查这个,如果你的屏幕被锁定,它将返回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;
}
© www.soinside.com 2019 - 2024. All rights reserved.