Android – Setting screen brightness from code behind

I ran into a problem today with trying to override the screen brightness for the current activity. I found there are 2 methods of changing your screen brightness, 1 which changed the whole system brightness or the other which is to change your current activity’s brightness.

I went for the latter however I came up against some problems when I tried to use the code I found here;

http://stackoverflow.com/a/5090578/276220

 I realised my eclipse was complaining because I had the project set as an android 2.1 project rather than the 2.3.3 handset which I was debugging on.
It would seem that you used to be able to just set it with;
public void SetBright(float value) 
{
    Window mywindow = getWindow();
    WindowManager.LayoutParams lp = mywindow.getAttributes();
    lp.screenBrightness = value;
    mywindow.setAttributes(lp);
}
However when google updated android with the option to set automatic brightness that method no longer worked. Therefore you had to check if the auto brightness had been set so that you could tell android that you were going to manually override the brightness
public void setBrightness(float brightness){ 
    try{
	int brightnessMode = android.provider.Settings.System.getInt(getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE);
 
        if (brightnessMode == android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
		android.provider.Settings.System.putInt(getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE, android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
	}
 
	WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
	layoutParams.screenBrightness = brightness;
	getWindow().setAttributes(layoutParams);
    } catch (Exception e){
        // do something useful
    }
}
I also found this which is a nice slider attached to the brightness, however their post looks pretty awful to read so I’d suggest check the stackoverflow post first before you try and understand this one 😀
http://android-er.blogspot.com/2011/02/change-system-screen-brightness-using.html