Android check if lockscreen is set

2019-02-17 04:51发布

问题:

i need to check if the lockscreen does have a Pin or something more secure (Password, Fingerprint etc.). Im able to check if there is a Pin, Password or a Pattern.

KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
    return keyguardManager.isKeyguardSecure();

My Problem is that i cant detect if the lockscreen is a Pattern or something lower. I tried this:

        int lockPatternEnable = Settings.Secure.getInt(cr, Settings.Secure.LOCK_PATTERN_ENABLED);

but its deprecated and throws me an error. I also tried this:

            long mode2 = Settings.Secure.getLong(contentResolver, "lockscreen.password_type");

but this ends with an SecurityException too.

Is there any way to detect if the lockscreen does have a pin (or higher) or it does a lock pattern or something lower? The KeyguardManager is not useful for me in that way :/

Any Help is appreciated! Thanks!

/edit

The Error for the first one is:

               Caused by: java.lang.SecurityException: Settings.Secure.lock_pattern_autolock is deprecated and no longer accessible. See API documentation for potential replacements.

The Exception for the second one is: W/System.err: android.provider.Settings$SettingNotFoundException: lockscreen.password_type

The Error just appears when youre using devices with Marshmallow or later (https://developer.android.com/reference/android/provider/Settings.Secure.html)

回答1:

I'm doing this : (inspired from https://gist.github.com/doridori/54c32c66ef4f4e34300f)

public boolean isDeviceScreenLocked() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return isDeviceLocked();
    } else {
        return isPatternSet() || isPassOrPinSet();
    }
}

/**
 * @return true if pattern set, false if not (or if an issue when checking)
 */
private boolean isPatternSet() {
    ContentResolver cr = context.getContentResolver();
    try {
        int lockPatternEnable = Settings.Secure.getInt(cr, Settings.Secure.LOCK_PATTERN_ENABLED);
        return lockPatternEnable == 1;
    } catch (Settings.SettingNotFoundException e) {
        return false;
    }
}

/**
 * @return true if pass or pin set
 */
private boolean isPassOrPinSet() {
    KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); //api 16+
    return keyguardManager.isKeyguardSecure();
}

/**
 * @return true if pass or pin or pattern locks screen
 */
@TargetApi(23)
private boolean isDeviceLocked() {
    KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); //api 23+
    return keyguardManager.isDeviceSecure();
}


回答2:

You will have to implement pre and post marshmallow functions to check this. You can switch your implementations during runtime based on SDK-Version.