2

I decided to post two question in one post, because it's quite same problem.

I need to know when screen is ON or OFF so i can turn LED. The second one I need to know if my applicaiton is in backgorund or it is in foreground, to manage sending notification on some actiong when app is in background.

Ozair Kafray
  • 13,351
  • 8
  • 59
  • 84
artouiros
  • 3,947
  • 12
  • 41
  • 54

3 Answers3

13

Adding answer for screen ON/OFF check:

// 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.

Jorge Fuentes González
  • 11,568
  • 4
  • 44
  • 64
  • the official documentation says `Note in particular that the device is still considered to be interactive while dreaming`. I found http://stackoverflow.com/a/28747907/1115059 to be more accurate and updated – Jaydeep Solanki Mar 12 '15 at 12:57
  • @Jaydeep Hmmm, interesting. Going to update the answer. Thank you! – Jorge Fuentes González Mar 12 '15 at 14:56
  • how to use getState() method in the background suppose when display goes off need to to some work in background .(ACTION_SCREEN_OFF deal with is user interactive or not but not with display on/off). any idea? Thanks – Milon Dec 07 '15 at 06:34
2

There have been similar questions on Stackoverflow earlier. Here are links to a few of them:

  1. How to determine if one of my activities is in the foreground

  2. android:how to check if application is running in background

  3. How can I tell if Android app is running in the foreground?

Community
  • 1
  • 1
Ozair Kafray
  • 13,351
  • 8
  • 59
  • 84
2

You can know if you're in the foreground or not through use of your activity's onWindowFocusChanged() callback; see http://developer.android.com/reference/android/view/Window.Callback.html

You can also create a broadcast receiver to capture SCREEN_ON and SCREEN_OFF events. Here is an example.

mah
  • 39,056
  • 9
  • 76
  • 93