Android: How to turn screen on and off programmatically?

I am going to assume you only want this to be in effect while your application is in the foreground.

This code:

params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);

Does not turn the screen off in the traditional sense. It makes the screen as dim as possible. In the standard platform there is a limit to how dim it can be; if your device is actually allowing the screen to turn completely off, then it is some peculiarity of the implementation of that device and not a behavior you can count on across devices.

In fact using this in conjunction with FLAG_KEEP_SCREEN_ON means that you will never allow the screen to go off (and thus the device to go into low-power mode) even if the particular device is allowing you to set the screen brightness to full-off. Keep this very strongly in mind. You will be using much more power than you would if the screen was really off.

Now for turning the screen back to regular brightness, just setting the brightness value should do it:

WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = -1;
getWindow().setAttributes(params);

I can’t explain why this wouldn’t replace the 0 value you had previously set. As a test, you could try putting a forced full brightness in there to force to that specific brightness:

WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1;
getWindow().setAttributes(params);

This definitely works. For example, Google’s Books apps uses this to allow you to set the screen brightness to dim while using a book and then return to regular brightness when turning that off.

To help debug, you can use “adb shell dumpsys window” to see the current state of your window. In the data for your window, it will tell you the current LayoutParams that have been set for it. Ensure the value you think is actually there.

And again, FLAG_KEEP_SCREEN_ON is a separate concept; it and the brightness have no direct impact on each other. (And there would be no reason to set the flag again when undoing the brightness, if you had already set it when putting the brightness to 0. The flag will stay set until you change it.)

Leave a Comment