change screen brightness when autobrightness enabled

818 views Asked by At

The code below to change screen brightness is not working when auto brightness of device is enabled:

Window w = getWindow();
WindowManager.LayoutParams lp = w.getAttributes();

lp.screenBrightness=0.09f;
getWindow().setAttributes(lp);

How to change this code for working on auto brightness too?

2

There are 2 answers

1
Melquiades On BEST ANSWER

DISCLAIMER: This code is kind of 'hackish', and might not work on all android versions and all android phones, and might not be the best code practice. I claim no responsibility if your device explodes, or it starts raining etc. :)

That being said, you might want to disable autobrightness temporarily:

Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);

And then re-enable it:

Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
0
D.Ford On

The following code is worked perfect on Android0.

   private void setBrightness(Activity activity, int brightness) {
            WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
            lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
            activity.getWindow().setAttributes(lp);
        }

It can be considered the priority of window attributes is higher than autobrightness.

You can check this logic in PowerManagerService.java -> updateDisplayPowerStateLocked.