I have a problem with lockscreen. Sometimes when I sleep the phone and then immediately after wake it up, onResume is called and then onPause which messes up my app. I thought that I could do a workaround and if lockscreen is displayed then ignore the logic that I have in onPause but I can't figure out how to check it. I tried to use PowerManger and KeyguardManager like suggested here but it didn't work. I also tried to check if activity hasWindowFocus() in onPause but it returns true even if lockscreen is showing. Is there any way to know if lockscreen is currently displayed?
Asked
Active
Viewed 254 times
1 Answers
0
Check this it will return true if your screen is locked.
/**
* 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;
}

Krishna Sony
- 1,286
- 13
- 27
-
This method checks if device is locked not if lockscreen is currently displayed. If I use it in onPause it will return true when I sleep the phone which is not what I want. – Michał Witanowski May 20 '20 at 10:19
-
Okay check this if it can help: https://stackoverflow.com/a/14352718/9523118 – Krishna Sony May 20 '20 at 10:32