Here's the relevant code:

 WindowManager.LayoutParams windowParams = getWindow().getAttributes();
 windowParams.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
 windowParams.screenBrightness = 0.0f;
 getWindow().setAttributes(windowParams);

I also tried setting screenBrightness to 0 (an integer rather than float), as well as the following line I found in a Stack Overflow answer:

this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

No dice. The screen dims, but does not turn off. The above code worked in previous Android versions. I just tested it in an emulator to make sure. Was a new method implemented to control the screen?

有帮助吗?

解决方案 4

From what I have found, it is no longer possible to reliably turn the screen off in newer version of Android. The only solution which appears to work is the one which requires the DEVICE_POWER permission, which is a restricted permission.

其他提示

Please call the following two functions to switch off your screen as your code is not consistent.

From Docs:

 public void goToSleep (long time)

Added in API level 1 Forces the device to go to sleep.

Overrides all the wake locks that are held. This is what happens when the power key is pressed to turn off the screen. Requires the DEVICE_POWER permission.

 public void wakeUp (long time)

Added in API level 17 Forces the device to wake up from sleep.

If the device is currently asleep, wakes it up, otherwise does nothing. This is what happens when the power key is pressed to turn on the screen.

Requires the DEVICE_POWER permission.

I'm not sure why what you're doing isn't working. This is a dirty hack but perhaps you could change the screen timeout to a very low time.

android.provider.Settings.System.putInt(getContentResolver(),
        Settings.System.SCREEN_OFF_TIMEOUT, time);

Say time=300 which is 300 milliseconds.

I don't know exactly what you are trying to accomplish here, but definitely for screen controlling like wake/sleep, you should take a look at the PowerManager class, is simple and easy to use: http://developer.android.com/reference/android/os/PowerManager.html

This is an example of how to use it:

protected void setScreenLock(boolean on){
    if(mWakeLock == null){
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK |
                                    PowerManager.ON_AFTER_RELEASE, TAG);
    }
    if(on){
     mWakeLock.acquire();
    }else{
        if(mWakeLock.isHeld()){
            mWakeLock.release();
        }
     mWakeLock = null;
    }

}

Regards!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top