Detecting when screen is locked

Solution 1:

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:

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