简体   繁体   中英

How to tell if device is sleeping

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?

((PowerManager) getSystemService(Context.POWER_SERVICE)).isScreenOn()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM