4

How can I check if the screen is unlocked (E.i. Turned on and not on lockscreen)?

PS. I'm not looking for the unlock event, which I know can be retrieved with an AdminDeviceReceiver, but I'm looking for an executable code that will return a boolean telling me whether or not the screen is unlocked.

Jakob Harteg
  • 9,587
  • 15
  • 56
  • 78
  • 1
    for screen On/Off you can use the Screen On/Off broadcast – Saqib Jan 14 '14 at 12:42
  • yes thanks, but I need to know if the screen is unlocked – Jakob Harteg Jan 14 '14 at 12:43
  • not sure but you may try to catch the touch screen event for device, it you can that means device is unlocked so been used – Saqib Jan 14 '14 at 12:46
  • 1
    possible duplicate of [How to find the screen is locked in android](http://stackoverflow.com/questions/9002032/how-to-find-the-screen-is-locked-in-android) – JanBo Jan 14 '14 at 12:49

5 Answers5

18

Try with this:

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

Taken from: Detecting when screen is locked

Also same answer : How to tell if user is on lock screen from service

Community
  • 1
  • 1
JanBo
  • 2,925
  • 3
  • 23
  • 32
4
KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            if( keyguardManager.inKeyguardRestrictedInputMode()) {
                System.out.println("~~~SCREEN LOCKED~~~");
            } else {
                System.out.println("~~~SCREEN NOT LOCKED~~~");
            }
Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243
3

!mKeyguardManager.isDeviceLocked()

Jacob Abraham
  • 915
  • 9
  • 8
2

Check the Screen Off State in your onPause Method using Power Manager

@Override
protected void onPause()
{
    super.onPause();

    // If the screen is off then the device has been locked
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    boolean isScreenOn = powerManager.isScreenOn();

    if (!isScreenOn) {

        // The screen has been locked 
        // do stuff...
    }
}
Sujewan
  • 1,023
  • 10
  • 25
1

As per google Doc inKeyguardRestrictedInputMode is Deprecated. Instead of You can use below method for phone is wake up or not.

private boolean isPhoneIsLockedOrNot(Context context) {
        boolean isPhoneLock = false;
        if (context != null) {
            KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            if (myKM != null && myKM.isKeyguardLocked()) {
                isPhoneLock = true;
            }
        }
        return isPhoneLock;
    }
Nik
  • 1,991
  • 2
  • 13
  • 30