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