Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if device is sleeping

Tags:

android

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?

like image 888
iterator Avatar asked Nov 23 '10 20:11

iterator


People also ask

How do I know if my phone is in sleep mode?

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.

How do I know if my android is in sleep mode?

Go to Apps. Select Settings. Select Display. Select Sleep or Screen Timeout.

How do I stop my device from going to sleep?

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.

What does it mean when your phone is asleep?

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.


2 Answers

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();
like image 68
A. Abramov Avatar answered Oct 13 '22 00:10

A. Abramov


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!

like image 32
satur9nine Avatar answered Oct 13 '22 00:10

satur9nine