简体   繁体   中英

Detect Always-On Display when trying to determine if the screen is off

I'm trying to figure out how to detect if the Display is Off on Android and I have a feeling that the Always-On Display on my S10 is affecting my results.

Currently, I'm using the logic found in this stackoverflow answer .

There is also a comment on that thread that says you should be able to use Display.FLAG_PRIVATE to check for Samsung's Always-On Display, but it doesn't explain how.

Using that information, I've put together this function. But it doesn't seem to work. The display seems to be counted as on almost always if i have the Always-On display enabled.

public boolean isScreenOn() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
        DisplayManager dm = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
        for (Display display : dm.getDisplays()) {
            if ((display.getFlags() & Display.FLAG_PRIVATE) != Display.FLAG_PRIVATE) {
                if (display.getState() != Display.STATE_OFF) {
                    return true;
                }
            }
        }
        return false;
    } else {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        //noinspection deprecation
        return pm.isScreenOn();
    }
}

I'm not sure if the way i'm checking the Display.FLAG_PRIVATE flag is correct, or if that will even help with the potential of the Always-On display affecting the result.

I found that the flags don't actually have anything to do with it. It seems that the display state will be one of several states including Display.STATE_DOZE_SUSPENDED , Display.STATE_DOZE and several others when the Always-On Display is active. So instead, I'm just checking for Display.STATE_ON and treating all other states as the display being turned off.

public boolean isScreenOn() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
        DisplayManager dm = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
        for (Display display : dm.getDisplays()) {
            if (display.getState() == Display.STATE_ON) {
                return true;
            }
        }
        return false;
    } else {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        //noinspection deprecation
        return pm.isScreenOn();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM