Detecting when screen is locked

AndroidScreen

Android Problem Overview


I've seen a couple of posts on here on how to check if the screen is locked, but none of it has been working for me. It all detects if the actual screen is off or not (not if it's locked).

I have a game in which music plays. When the lock button is pressed, it continues to play. I originally had the music stopping in OnStop, but the application would restart after getting locked, so the music would eventually start up again.

Then, I added KeyboardHidden|orientation to the manifest. This makes it so it doesn't restart the app, but OnStop doesn't seem to get called anymore.

I've tried using PowerManager to see if the screen is on/off, which works, but doesn't help. (I can get the music to stop there, but as soon as you hit the lock button again, the music starts right back up)

Android Solutions


Solution 1 - Android

There is a better way:

KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if( myKM.inKeyguardRestrictedInputMode()) {
 //it is locked
} else {
 //it is not locked
}

No need for broadcastRecievers, permissions or anything similar.

Note: It doesn't work when user has set his/her screen lock to none in settings-->security-->screenlock-->none

Solution 2 - Android

This link might be helpful to others for two things at one place.

Check if the Device is Locked Or Not:

KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
boolean isPhoneLocked = myKM.inKeyguardRestrictedInputMode();

(Note: above method doesn't work if screenlock is set to none in settings-->security-->screenlock.)

Check If Device is Awake or in Sleep Mode:(for Sdk Version > L Preview < Sdk Version)

PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
isScreenAwake = (Build.VERSION.SDK_INT < 20? powerManager.isScreenOn():powerManager.isInteractive());

Solution 3 - Android

The Above solution is correct but when i get output it gave me an output locked when screen off and and locked when screen on but doesn't gave unlock output when i unlocked device after putting pattern for unlock. So Here is my solution.

private void registerBroadcastReceiver() {
    
     final IntentFilter theFilter = new IntentFilter();
    /** System Defined Broadcast */
    theFilter.addAction(Intent.ACTION_SCREEN_ON);
    theFilter.addAction(Intent.ACTION_SCREEN_OFF);
    theFilter.addAction(Intent.ACTION_USER_PRESENT);

    BroadcastReceiver screenOnOffReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String strAction = intent.getAction();

            KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if(strAction.equals(Intent.ACTION_USER_PRESENT) || strAction.equals(Intent.ACTION_SCREEN_OFF) || strAction.equals(Intent.ACTION_SCREEN_ON)  )
                if( myKM.inKeyguardRestrictedInputMode())
                {
                    System.out.println("Screen off " + "LOCKED");
                } else
                {
                    System.out.println("Screen off " + "UNLOCKED");
                }

        }
    };

    getApplicationContext().registerReceiver(screenOnOffReceiver, theFilter);
}

after that this will give me output like

I/System.out:LOCKED 
when i off the mobile screen
I/System.out:LOCKED
when i on the mobile screen
I/System.out:UNLOCKED
when i unlock the mobile after pattern lock

Solution 4 - Android

Taken from this link: https://gist.github.com/Jeevuz/4ec01688083670b1f3f92af64e44c112

/**
 * 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;
}

Solution 5 - Android

You can use KeyguardManager class to check if the screen is locked or not. Below is the code snippet written in Kotlin.

    val keyguardManager: KeyguardManager = context?.getSystemService 
    (Context.KEYGUARD_SERVICE) as KeyguardManager

    if (keyguardManager.isDeviceLocked) {
       // device locked logic goes here 
    } else {
       // device unlocked case
    }

Solution 6 - Android

I would suggest this:

private void registerBroadcastReceiver() {
	final IntentFilter theFilter = new IntentFilter();
	/** System Defined Broadcast */
	theFilter.addAction(Intent.ACTION_SCREEN_ON);
	theFilter.addAction(Intent.ACTION_SCREEN_OFF);

	BroadcastReceiver screenOnOffReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String strAction = intent.getAction();

			KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);

			if (strAction.equals(Intent.ACTION_SCREEN_OFF) || strAction.equals(Intent.ACTION_SCREEN_ON)) 
			{
				if( myKM.inKeyguardRestrictedInputMode()) 
				{
					System.out.println("Screen off " + "LOCKED");
				} else 
				{
					System.out.println("Screen off " + "UNLOCKED");
				}
			}
		}
	};

	getApplicationContext().registerReceiver(screenOnOffReceiver, theFilter);
}

The above answer from @Shaul Rosenzweig combined with the other post available to detect screen on and off status. I tested this solution on Samsung Galaxy S4 Mini and worked well for me.

Solution 7 - Android

The Below code shows if the screen is locked or not.

 private void checkPhoneScreenLocked(){
        KeyguardManager myKM = (KeyguardManager) getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
        if( myKM.isKeyguardLocked()) {
            System.out.println("Phone is locked");
        } else {
            System.out.println("Phone is not locked");
        }
    }

enter image description here

DrawBack:-We can check the phone is locked or not.only if the user has selected the any security patters other than none.

Solution 8 - Android

Luv Kumar's answer works but it only registers when user explicitly locks the screen (by pressing the lock button). Besides that, I want my app to tell when screen goes off (e.g. screen timeout) just did that:

Just added another option to myKM.inKeyguardRestrictedInputMode()

if( myKM.inKeyguardRestrictedInputMode() || (strAction.equals(Intent.ACTION_SCREEN_OFF)) 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRyanView Question on Stackoverflow
Solution 1 - AndroidShaul RosenzweigView Answer on Stackoverflow
Solution 2 - AndroidSagar ShahView Answer on Stackoverflow
Solution 3 - AndroidLoveView Answer on Stackoverflow
Solution 4 - AndroidAlécio CarvalhoView Answer on Stackoverflow
Solution 5 - AndroidAnubhavView Answer on Stackoverflow
Solution 6 - Androidclass AndroidView Answer on Stackoverflow
Solution 7 - Androidvinay shettyView Answer on Stackoverflow
Solution 8 - AndroiddanjarView Answer on Stackoverflow