Here's my scenario. I have an app that is playing backgound sounds. Using the BroadcastReceiver I can tell when the display turns off, and then kill the sounds. I can also tell if the screen turns back on. However, if the device is in the lock state I don't want the audio to start. Therefore I wait for the ACTION_USER_PRESENT intent to signal. That all works, except that if the user turns the screen back on quickly after it was turned off, you don't get the lock screen or the ACTION_USER_PRESENT message. So, is there a way to tell, when the screen turns back on, if the device is locked or not, which I guess also means sleeping or not?
Asked
Active
Viewed 8,543 times
12
-
If the device is actually sleeping, the application processor is not executing code. Screen locked is something else entirely. – Chris Stratton Nov 23 '10 at 20:58
-
1Fair enough. So how to tell if the screen is locked? – iterator Nov 23 '10 at 21:09
-
http://stackoverflow.com/questions/3170563/android-detect-phone-lock-event – Jared Burrows May 28 '13 at 06:36
-
Thanks for your question, 10 years later I was looking for an answer and was pointed in the right direction. I'll post what I've found. – A. Abramov Jun 08 '20 at 13:44
4 Answers
12
((PowerManager) getSystemService(Context.POWER_SERVICE)).isScreenOn()

Dhaval Parmar
- 18,812
- 8
- 82
- 177

Buda Gavril
- 21,409
- 40
- 127
- 196
-
isScreenOn() is deprecated. You should use isInteractive() instead. – Manuel Domínguez Jul 17 '20 at 07:23
10
You can try the KeyguardManager to check if the device is locked. Here is some code (I haven't tried this myself):
KeyguardManager kgMgr = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
boolean showing = kgMgr.inKeyguardRestrictedInputMode();
Good luck!

satur9nine
- 13,927
- 5
- 80
- 123
-
1I tried, but "showing" returned false whether the screen was locked or not. – iterator Nov 23 '10 at 21:33
-
Great solution 10 years ago, sadly it's deprecated. Posted an updated answer. – A. Abramov Jun 08 '20 at 13:40
1
Satur9nine's solution was right at the time, but since then isKeyguardRestricatedInputMode()
was deprecated. Some powerManager related functionalities are now deprecated as well.
There's a newer, more accurate solution: isKeyguardLocked() for whether the device is locked, and a different approach to obtain whether the screen is interactive; You're looking for a combination of both.
KeyguardManager appKeyguard = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
PowerManager appPowerManager = (PowerManager) getSystemService(Context,POWER_SERVICE);
boolean showing = !appKeyguard.isKeyguardLocked() && appPowerManager.isInteractive();

A. Abramov
- 1,823
- 17
- 45
0
((PowerManager) getSystemService(Context.POWER_SERVICE)).isScreenOn()
tells if the screen is on. So, it gets true if the screen is on but the device is locked. Instead,
inKeyguardRestrictedInputMode()
gets true just if the device is locked.

Dekra
- 554
- 5
- 15