简体   繁体   中英

Is there a method to check if the screen is turned on or off?

I need a service to take gps updates, but only, when the screen is turned on. Is there a method to do this? My idea was to work with a Alarm manager and a alarm reciever class that cheks if the screen is turned on and af it is starting a service. But how could the Alarmreciever check if the screen is turned on?

You can use this method to check if screens is on/off.

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

Call it like

isScreenOn(YourActivity.this);

try this

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        boolean isScreenOn = pm.isScreenOn();
        if (isScreenOn){
            //Screen is on
        }else {
            //Screen is off
        }

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