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?
The device's screen will turn black and it will look like it is turned off. This is actually the sleep mode. In sleep mode, the device will be able to wake up very quickly when you press on a key. Some apps may actually continue running in the background when the device is asleep.
Go to Apps. Select Settings. Select Display. Select Sleep or Screen Timeout.
Open Settings. Tap Display. Tap Sleep or Screen timeout. Select how long you want your Android smartphone or tablet screen to stay on before turning off due to inactivity.
Device is asleep when there is not running application that prevents it from sleeping. So: 1. The screen is off (while it's on there is always some running app, e.g.Launcher) 2. There is no running service (e.g. music, downloads) - no CPU locks.
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();
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With