26

I am wondering to know how to detect screen dim or brightness on Android 1.6.

I've found a solution on API Level 7. It is easy to develop :

PowerManager pm = (PowerManager)
getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();

But I need a solution for Android 1.x.

Can you suggest me ?

Thanks.

Ferdinand
  • 1,193
  • 4
  • 23
  • 43

2 Answers2

25

For screen on-off state, you can try with ACTION_SCREEN_ON and ACTION_SCREEN_OFF Intents, as shown in this blog post: http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/

Elltz
  • 10,730
  • 4
  • 31
  • 59
Nacho L.
  • 9,582
  • 2
  • 25
  • 25
  • ACTION_SCREEN_OFF intent depends on user is not interactive. it don't deal will device display/screen is off or not. – Milon Dec 07 '15 at 06:08
23

The approach with the ACTION_SCREEN_ON did not work for me. After some different solutions this code finally solved the problem for me:

/**
 * Is the screen of the device on.
 * @param context the context
 * @return true when (at least one) screen is on
 */
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 screenOn = false;
        for (Display display : dm.getDisplays()) {
            if (display.getState() != Display.STATE_OFF) {
                screenOn = true;
            }
        }
        return screenOn;
    } else {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        //noinspection deprecation
        return pm.isScreenOn();
    }
}
Elltz
  • 10,730
  • 4
  • 31
  • 59
userM1433372
  • 5,345
  • 35
  • 38
  • 2
    Had to add an exclusion on my OnePlus One because there was a Display with the name "Pen off-screen display" which was always STATE_ON. Apart from that, this works great, many thanks! :) – tommed Jul 07 '15 at 21:04
  • how can i check state of the display using Display.getState() in the background or when display goes off I need to some stuff in the background. any Idea? @tommed – Milon Dec 07 '15 at 06:12
  • Use a service, checking screen state in the background is no different to checking anything else in the background on android. – tommed Dec 07 '15 at 07:15
  • Note that with this on newer phones such as the s7's with the always on screen if you want to class "always on" - ie the black screen with the time on as off, then it's state will be either state State.STATE_DOZE or State.STATE_DOZE_SUSPEND – Andrew Jun 18 '16 at 23:17