how to check screen on/off status in onStop()?

守給你的承諾、 提交于 2019-12-17 22:32:50

问题


as mentioned here, when the screen goes off, the onStop() of current Activity will be called. I need to check the screen on/off status when the onStop() of my Activity is called. so I have registered a BroadcastReceiver for these actions(ACTION_SCREEN_ON AND ACTION_SCREEN_OFF) to record the current on/off status(and they work properly, I have logged!).
but when I turn off the screen and check the on/off status in the onStop , it says the screen is on. why? I think the receiver must receive the ACTION_SCREEN_OFF before onStop is called so what's wrong?


回答1:


You can try to use PowerManager system service for this purpose, here is example and official documentation (note this method was added in API level 7):

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();

EDIT:

isScreenOn() method is deprecated API level 21. You should use isInteractive instead:

boolean isScreenOn = pm.isInteractive();

http://developer.android.com/reference/android/os/PowerManager.html#isInteractive()



来源:https://stackoverflow.com/questions/19350258/how-to-check-screen-on-off-status-in-onstop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!