There's a better way than using BroadcastReceivers:
// If you use API20 or more:
DisplayManager dm = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
for (Display display : dm.getDisplays()) {
if (display.getState() != Display.STATE_OFF) {
return true;
}
}
return false;
// If you use less than API20:
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
if (powerManager.isScreenOn()){ return true; }
Note that Display.getState()
can also return STATE_DOZE
and STATE_DOZE_SUSPEND
which means that the screen is on in an special way. More info on Display.getState()
and his return values here: http://developer.android.com/reference/android/view/Display.html#getState()
Also note that although official documentation recommends using isInteractive()
instead of isScreenOn()
, if you really want to know the status of the screen, Display.getState()
is a better option because of the 'special' conditions that sets the screen on while the device is not interactive.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…