开发者

Getting if Screen ON/OFF and if Application is in Background/Foreground

开发者 https://www.devze.com 2023-03-12 12:46 出处:网络
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 backgor

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 s开发者_如何学JAVAending notification on some actiong when app is in background.


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.


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消