Android 2.2: Adjusting screen brightness

Johan picture Johan · Jan 7, 2011 · Viewed 9.7k times · Source
    public void SetBright(float value) 
{
    Window mywindow = getWindow();

    WindowManager.LayoutParams lp = mywindow.getAttributes();

            lp.screenBrightness = value;

            mywindow.setAttributes(lp);
}

I want to adjust the screen brightness. But nothing happens when i try using this method. Could it be because i use the KEEP_SCREEN_ON flag?

Answer

Adam Thomas picture Adam Thomas · Feb 23, 2011

Make sure that "Auto Brightness" is not enabled prior to setting the screen brightness. You can do this manually in Settings>Display or using code if you are using Android 2.2 or above SDK.

Something like:

int brightnessMode = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE);
if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
    Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}

WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.screenBrightness = 0.5F; // set 50% brightness
getWindow().setAttributes(layoutParams);

Ensure the value is between 0.0F and 1.0F. A value of -1.0F uses the default brightness stored in the preferences. Per the documentation "A value of less than 0, the default, means to use the preferred screen brightness. 0 to 1 adjusts the brightness from dark to full bright."