How to tell if device is sleeping

后端 未结 4 1060
我寻月下人不归
我寻月下人不归 2020-12-31 09:40

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

相关标签:
4条回答
  • 2020-12-31 10:08

    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();
    
    0 讨论(0)
  • 2020-12-31 10:18
    ((PowerManager) getSystemService(Context.POWER_SERVICE)).isScreenOn()
    
    0 讨论(0)
  • 2020-12-31 10:24
    ((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.

    0 讨论(0)
  • 2020-12-31 10:25

    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!

    0 讨论(0)
提交回复
热议问题