Usman Riaz Usman Riaz - 5 months ago 45
Android Question

Change the System Brightness Programmatically

i want to change the system brightness programmatically. for that purpose i am using this code:

WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = (255);

because i heard that max value is 255.

but it does nothing.please suggest any thing that can change the brightness.


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();

               // To handle the auto
                Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
 //Get the current system brightness
                brightness = 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");

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
            System.putInt(cResolver, 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

Permission in manifest:

<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>