How can I tell if the screen is on in android?

Solution 1:

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.

Solution 2:

This is how you should do it:

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
boolean result= VERSION.SDK_INT>=VERSION_CODES.KITKAT_WATCH&&powerManager.isInteractive()||VERSION.SDK_INT<VERSION_CODES.KITKAT_WATCH&&powerManager.isScreenOn();
return result;

Solution 3:

I'm using the following function:

public boolean isInteractive() {
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH 
        ? powerManager.isInteractive() 
        : powerManager.isScreenOn();
}