Ryan
Ryan

Reputation: 957

Detecting when screen is locked

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)

Upvotes: 71

Views: 79754

Answers (9)

Anubhav
Anubhav

Reputation: 2180

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.isKeyguardLocked) {
   // device locked logic goes here 
} else {
   // device unlocked case
}

Upvotes: 5

Harshal Pudale
Harshal Pudale

Reputation: 268

Use KeyguardManager.isDeviceLocked to detect if the device is currently locked and requires a PIN, pattern or password to unlock.

Ref: https://developer.android.com/reference/android/app/KeyguardManager#isDeviceLocked()

fun isDeviceLocked(context: Context): Boolean {
    return (context.getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager).isDeviceLocked
}

Upvotes: 0

vinay shetty
vinay shetty

Reputation: 981

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.

Upvotes: 3

Sagar Shah
Sagar Shah

Reputation: 4292

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());

Upvotes: 32

psydj1
psydj1

Reputation: 260

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)) 

Upvotes: 0

Al&#233;cio Carvalho
Al&#233;cio Carvalho

Reputation: 13647

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

Upvotes: 14

Love
Love

Reputation: 205

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

Upvotes: 18

Shaul Rosenzweig
Shaul Rosenzweig

Reputation: 1221

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

Upvotes: 112

class Android
class Android

Reputation: 761

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.

Upvotes: 2

Related Questions