I have solved this problem today.
As the first you have to put a permission into your AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
Where is the exact place to put it in the file?
<manifest>
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<application>
<activity />
</application>
</manifest>
This permission says, that you are allowed to change settings that affect other applications too.
Now you can set brightness automatic mode on and off
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC); //this will set the automatic mode on
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); //this will set the manual mode (set the automatic mode off)
Is the automatic mode turned on or off right now? You can get the information
int mode = -1;
try {
mode = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE); //this will return integer (0 or 1)
} catch (Exception e) {}
So, if you want to change brightness manually, you are supposed to set the manual mode first and after that you can change the brightness.
note: SCREEN_BRIGHTNESS_MODE_AUTOMATIC is 1
note: SCREEN_BRIGHTNESS_MODE_MANUAL is 0
You should use this
if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
//Automatic mode
} else {
//Manual mode
}
instead of this
if (mode == 1) {
//Automatic mode
} else {
//Manual mode
}
Now you can change the brightness manually
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightness); //brightness is an integer variable (0-255), but dont use 0
and read brightness
try {
int brightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS); //returns integer value 0-255
} catch (Exception e) {}
Now everything is set properly, but... you can't see the change yet.
You need one more thing to see the change!
Refresh the screen... so do this:
try {
int br = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS); //this will get the information you have just set...
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = (float) br / 255; //...and put it here
getWindow().setAttributes(lp);
} catch (Exception e) {}
Don't forget the permission...
<uses-permission android:name="android.permission.WRITE_SETTINGS" />