如果API级别为4,如何检测屏幕是打开还是关闭?

Fer*_*and 26 android

我想知道如何在Android 1.6上检测屏幕暗淡或亮度.

我在API Level 7上找到了一个解决方案.它很容易开发:

PowerManager pm = (PowerManager)
getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();
Run Code Online (Sandbox Code Playgroud)

但我需要Android 1.x的解决方案.

你能建议我吗?

谢谢.

Nac*_* L. 24

对于屏幕开关状态,您可以尝试使用ACTION_SCREEN_ONACTION_SCREEN_OFF Intents,如本博客文章所示:http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents /


use*_*372 23

这种做法ACTION_SCREEN_ON对我没用.经过一些不同的解决方案,这段代码终于解决了我的问题:

/**
 * 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不得不在我的OnePlus One上添加一个排除项,因为有一个名为"Pen off-screen display"的显示器,它始终是STATE_ON.除此之外,这非常有效,非常感谢!:) (2认同)