I want to change the system brightness programmatically. For that purpose I am using this code:
WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = (255);
window.setAttributes(lp);
because I heard that max value is 255.
but it does nothing. Please suggest any thing that can change the brightness. Thanks
You can use following :
//Variable to store brightness value
private int brightness;
//Content resolver used as a handle to the system's settings
private ContentResolver cResolver;
//Window object, that will store a reference to the current window
private Window window;
In your onCreate write:
//Get the content resolver
cResolver = getContentResolver();
//Get the current window
window = getWindow();
try
{
// To handle the auto
Settings.System.putInt(cResolver,
Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
//Get the current system brightness
brightness = Settings.System.getInt(cResolver, Settings.System.SCREEN_BRIGHTNESS);
}
catch (SettingNotFoundException e)
{
//Throw an error case it couldn't be retrieved
Log.e("Error", "Cannot access system brightness");
e.printStackTrace();
}
Write the code to monitor the change in brightness.
then you can set the updated brightness as follows:
//Set the system brightness using the brightness variable value
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
//Get the current window attributes
LayoutParams layoutpars = window.getAttributes();
//Set the brightness of this window
layoutpars.screenBrightness = brightness / (float)255;
//Apply attribute changes to this window
window.setAttributes(layoutpars);
Permission in manifest:
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
For API >= 23, you need to request the permission through Settings Activity, described here: Can't get WRITE_SETTINGS permission