Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 330
Soheil Avatar asked Oct 13 '13 21:10

Soheil


People also ask

When onPause method is called in android?

onPause. Called when the Activity is still partially visible, but the user is probably navigating away from your Activity entirely (in which case onStop will be called next). For example, when the user taps the Home button, the system calls onPause and onStop in quick succession on your Activity .


2 Answers

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()

like image 154
Alexander Semenov Avatar answered Oct 20 '22 09:10

Alexander Semenov


As mentioned in this answer to a similar question. In API 21 and above we can use the DisplayManager to determine the state of the display. This has the advantage of supporting the querying of multiple displays:

DisplayManager dm = (DisplayManager) 
context.getSystemService(Context.DISPLAY_SERVICE);
for (Display display : dm.getDisplays()) {
    if (display.getState() != Display.STATE_OFF) {
        return true;
    }
}
return false;

Depending upon your circumstance it might be more appropriate to query the display that a particular view is being displayed on:

myView.getDisplay().getState() != Display.STATE_OFF
like image 3
Rem-D Avatar answered Oct 20 '22 09:10

Rem-D