48

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

itsmysterybox
  • 2,218
  • 3
  • 18
  • 25
Usman Riaz
  • 2,720
  • 6
  • 40
  • 64
  • similar question : http://stackoverflow.com/questions/3737579/changing-screen-brightness-programmatically-in-android – Dhairya Vora Aug 19 '13 at 11:33
  • possible duplicate of [Can't apply system screen brightness programmatically in Android](http://stackoverflow.com/questions/5032588/cant-apply-system-screen-brightness-programmatically-in-android) – bummi Sep 22 '14 at 13:23
  • This is an old question. I have put complete answer at the bottom of this page. Hope it will save everyone's time. – Hitesh Sahu Oct 27 '20 at 20:06

16 Answers16

54

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

Eric
  • 12,320
  • 4
  • 53
  • 63
Ritesh Gune
  • 16,050
  • 6
  • 41
  • 70
  • 1
    Here i have to change the brightness variable with my variable? like between 0 - 255 ? ? ? – Usman Riaz Aug 19 '13 at 12:10
  • I got error - "SCREEN_BRIGHTNESS cannot be resolved or is not a field" for System.SCREEN_BRIGHTNESS. – Ganpat Jan 02 '14 at 11:42
  • @Terril, any particular reason to suggest the edit with code to handle auto?? :) – Ritesh Gune May 09 '14 at 11:22
  • 1
    Some time the brightness is in auto mode in such case we'll have to disable it first then do the snippet you have shared. Put the answer you have shared is pretty good. – Terril Thomas May 09 '14 at 11:29
  • @RiteshGune can u tell me i m only able to set values 0.1,0.2 and failed to set values 0.3,0.4,0.5 why ? my code is here http://paste.ofcode.org/ARPumKhgt6RVFuVnisyAxQ – Erum Jan 06 '15 at 06:13
  • 2
    This solution is not working for me. I am not getting any error but at the same time there is no change in screen display. – Charu Aug 24 '16 at 07:02
  • for those who get SCREEN_BRIGHTNESS cannot be resolved or is not a field" you can use this : Settings.System.SCREEN_BRIGHTNESS – Oussaki Sep 11 '17 at 11:57
  • 1
    I can use either System.putInt method or the window's layout params method right? they both achieve the same result in separate why would i need both? @RiteshGune – Itay Feldman Jul 31 '18 at 08:41
17

I had the same problem.

Two solutions:

here, brightness =(int) 0 to 100 range as i am using progressbar

1 SOLUTION

float brightness = brightness / (float)255;
WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.screenBrightness = brightness;
        getWindow().setAttributes(lp);

2 SOLUTION

I just used dummy activity to call when my progress bar stop seeking.

 Intent intent = new Intent(getBaseContext(), DummyBrightnessActivity.class);
                    Log.d("brightend", String.valueOf(brightness / (float)255));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //this is important
                    //in the next line 'brightness' should be a float number between 0.0 and 1.0
                    intent.putExtra("brightness value", brightness / (float)255); 
                    getApplication().startActivity(intent);

Now coming to the DummyBrightnessActivity.class

 public class DummyBrightnessActivity extends Activity{

private static final int DELAYED_MESSAGE = 1;

private Handler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);            
    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == DELAYED_MESSAGE) {
                DummyBrightnessActivity.this.finish();
            }
            super.handleMessage(msg);
        }
    };
    Intent brightnessIntent = this.getIntent();
    float brightness = brightnessIntent.getFloatExtra("brightness value", 0);
    WindowManager.LayoutParams lp = getWindow().getAttributes();
    lp.screenBrightness = brightness;
    getWindow().setAttributes(lp);

    Message message = handler.obtainMessage(DELAYED_MESSAGE);
    //this next line is very important, you need to finish your activity with slight delay
    handler.sendMessageDelayed(message,200); 
}

}

don't forget to register DummyBrightnessActivity to manifest.

hope it helps!!

Bhoomika Brahmbhatt
  • 7,032
  • 3
  • 25
  • 43
  • I am Doing it in a Custom Dialog. and it is not working. again i want to change overall system brightness. i run the code and then check system settings brightness and it was not effected – Usman Riaz Aug 19 '13 at 11:58
  • first check it with static value in `brightness` between 0 to 100..then use dynamic value..put – Bhoomika Brahmbhatt Aug 19 '13 at 12:02
  • Solution TWO: why the hell do you need dummy Activity? Look terribly inefficient. – Sevastyan Savanyuk Oct 11 '18 at 19:16
  • This is the perfect solution and should be accepted! Because there is no need for "android.permission.WRITE_SETTINGS" in the manifest & but this does the job – Arun K Babu Jul 04 '20 at 21:35
13

Reference link

  WindowManager.LayoutParams layout = getWindow().getAttributes();
 layout.screenBrightness = 1F;
  getWindow().setAttributes(layout);     
Amit Prajapati
  • 9,444
  • 7
  • 42
  • 71
10

I tried several solutions that others posted and none of them worked exactly right. The answer from geet is basically correct but has some syntactic errors. I created and used the following function in my application and it worked great. Note this specifically changes the system brightness as asked in the original question.

public void setBrightness(int brightness){

    //constrain the value of brightness
    if(brightness < 0)
        brightness = 0;
    else if(brightness > 255)
        brightness = 255;


    ContentResolver cResolver = this.getApplicationContext().getContentResolver();
    Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);

}
user3092247
  • 101
  • 1
  • 2
10

In my case, I only want to light up the screen when I display a Fragment and not change the system wide settings. There is a way to only change the brightness for your Application/Activity/Fragment. I use a LifecycleObserver to adjust the screen brightness for one Fragment:

class ScreenBrightnessLifecycleObserver(private val activity: WeakReference<Activity?>) :
    LifecycleObserver {

    private var defaultScreenBrightness = 0.5f

    init {
        activity.get()?.let {
            defaultScreenBrightness = it.window.attributes.screenBrightness
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun lightUp() {
        adjustScreenBrightness(1f)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun lightDown() {
        adjustScreenBrightness(defaultScreenBrightness)
    }

    private fun adjustScreenBrightness(brightness: Float) {
        activity.get()?.let {
            val attr = it.window.attributes
            attr.screenBrightness = brightness
            it.window.attributes = attr
        }
    }
}

And add the LifecycleObserver such as this in your Fragment:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        // ...

        lifecycle.addObserver(ScreenBrightnessLifecycleObserver(WeakReference(activity)))

        // ...

        return binding.root
}
Paul Spiesberger
  • 4,334
  • 1
  • 37
  • 47
  • 2
    that's a really nice and elegant solution! – Sergii N. Oct 01 '19 at 08:52
  • 1
    Great solution. One suggestion: since your class is LifecycleObserver, you can make your Activity reference nullable and set it to null in Lifecycle.Event.ON_DESTROY. You can make your Activity member nullable, but constructor param non-nullable - then you can calculate defaultScreenBrightness based on non-nullable constructor param - without the "null case" and then you don't need the default 0.5 value. – Singed May 07 '20 at 10:15
4

this worked for me till kitkat 4.4 but not in android L

private void stopBrightness() {
    Settings.System.putInt(this.getContentResolver(),
            Settings.System.SCREEN_BRIGHTNESS, 0);
}
Jenish Rabadiya
  • 6,480
  • 5
  • 31
  • 57
user3475052
  • 276
  • 2
  • 15
3

This is the complete code on how to change system brightness

    private SeekBar brightbar;

    //Variable to store brightness value
    private int brightness;
    //Content resolver used as a handle to the system's settings
    private ContentResolver Conresolver;
    //Window object, that will store a reference to the current window
    private Window window;

    /** Called when the activity is first created. */
    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //Instantiate seekbar object
        brightbar = (SeekBar) findViewById(R.id.ChangeBright);

        //Get the content resolver
        Conresolver = getContentResolver();

        //Get the current window
        window = getWindow();

        brightbar.setMax(255);

        brightbar.setKeyProgressIncrement(1);

        try {
            brightness = System.getInt(Conresolver, System.SCREEN_BRIGHTNESS);
        } catch (SettingNotFoundException e) {
            Log.e("Error", "Cannot access system brightness");
            e.printStackTrace();
        }

        brightbar.setProgress(brightness);

        brightbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            public void onStopTrackingTouch(SeekBar seekBar) {
                System.putInt(Conresolver, System.SCREEN_BRIGHTNESS, brightness);

                LayoutParams layoutpars = window.getAttributes();

                layoutpars.screenBrightness = brightness / (float) 255;

                window.setAttributes(layoutpars);
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                if (progress <= 20) {

                    brightness = 20;
                } else {

                    brightness = progress;
                }
            }
        });
    }

Or you may check this tutorial for complete code
happy coding:)

Sanoop Surendran
  • 3,241
  • 3
  • 24
  • 46
dondondon
  • 743
  • 6
  • 4
2
private SeekBar Brighness = null;

@Override
protected void onCreate(Bundle savedInstanceState) {

     super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_lcd_screen_setting);
     initUI();
     setBrightness();
}

private void setBrightness() {

    Brighness.setMax(255);
    float curBrightnessValue = 0;

    try {
        curBrightnessValue = android.provider.Settings.System.getInt(
                getContentResolver(),
                android.provider.Settings.System.SCREEN_BRIGHTNESS);
    } catch (Settings.SettingNotFoundException e) {
        e.printStackTrace();
    }
    int screen_brightness = (int) curBrightnessValue;
    Brighness.setProgress(screen_brightness);

    Brighness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        int progress = 0;


        @Override
        public void onProgressChanged(SeekBar seekBar, int progresValue,
                                      boolean fromUser) {
            progress = progresValue;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // Do something here,
            // if you want to do anything at the start of
            // touching the seekbar
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            android.provider.Settings.System.putInt(getContentResolver(),
                    android.provider.Settings.System.SCREEN_BRIGHTNESS,
                    progress);
        }
    });
}

initUI(){
   Brighness = (SeekBar) findViewById(R.id.brightnessbar);
}

Add this in manifest

<uses-permission android:name="android.permission.WRITE_SETTINGS"
 tools:ignore="ProtectedPermissions"/>
Kishan Thakkar
  • 197
  • 2
  • 10
arshad shaikh
  • 573
  • 6
  • 11
2
WindowManager.LayoutParams params = getWindow().getAttributes();
    params.screenBrightness = 10; // range from 0 - 255 as per docs
    getWindow().setAttributes(params);
    getWindow().addFlags(WindowManager.LayoutParams.FLAGS_CHANGED);

This worked for me. No need of a dummy activity. This works only for your current activity.

prago
  • 4,425
  • 5
  • 21
  • 27
2
<uses-permission android:name="android.permission.WRITE_SETTINGS"
        tools:ignore="ProtectedPermissions" />

android.provider.Settings.System.putInt(getContentResolver(),
                    android.provider.Settings.System.SCREEN_BRIGHTNESS,
                    progress);
  • you have to ask for Write permission first. Without that it'll throw " java.lang.SecurityException: com.myExamlpe was not granted this permission: android.permission.WRITE_SETTINGS." and the app will crash. – Tarun Kumar Dec 14 '20 at 11:40
2

Complete Answer

I did not wanted to use Window Manager to set brightness. I wanted the brighness to reflect on System level as well as on UI. None of the above answer worked for me. Finally this approach worked for me.

Add Write setting permission in Android Manifest

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

Write Settings is a Protected settings so request user to allow Writing System settings:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Settings.System.canWrite(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            }
        }

Now you can set Brightness easily

            ContentResolver cResolver = getContentResolver();
            Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);

brighness value should be in range of 0-255 so if you have aslider with range (0-max) than you can normalize the value in range of (0-255)

private float normalize(float x, float inMin, float inMax, float outMin, float outMax) {
    float outRange = outMax - outMin;
    float inRange  = inMax - inMin;
  return (x - inMin) *outRange / inRange + outMin;
}

Finally you can now change range of 0-10 slider to 0-255 like this

            float brightness = normalize(progress, 0, 10, 0.0f, 255.0f);

Hope it will save your time.

Hitesh Sahu
  • 31,496
  • 11
  • 150
  • 116
2

Best solution

WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 0.5F ; getWindow().setAttributes(layout);

// 0.5 is %50
// 1 is %100
Suraj Rao
  • 28,186
  • 10
  • 88
  • 94
  • Although the system setting for brightness is not affected by this, I believe your answer should be enough for most people. I like that is doesn't require a permission. – Tinus81 Feb 01 '21 at 21:20
1

Please Try this , it's May help you. Worked fine for me

According to my experience

 1st method.
                     WindowManager.LayoutParams lp = getWindow().getAttributes();  
                 lp.screenBrightness = 75 / 100.0f;  
                 getWindow().setAttributes(lp);

where the brightness value very according to 1.0f.100f is maximum brightness.

The above mentioned code will increase the brightness of the current window. If we want to increase the brightness of the entire android device this code is not enough, for that we need to use

   2nd method.



       android.provider.Settings.System.putInt(getContentResolver(),
                         android.provider.Settings.System.SCREEN_BRIGHTNESS, 192); 

Where 192 is the brightness value which very from 1 to 255. The main problem of using 2nd method is it will show the brightness in increased form in android device but actually it will fail to increase android device brightness.This is because it need some refreshing.

That is why I find out the solution by using both codes together.

            if(arg2==1)
                {

         WindowManager.LayoutParams lp = getWindow().getAttributes();  
                 lp.screenBrightness = 75 / 100.0f;  
                 getWindow().setAttributes(lp);  
                 android.provider.Settings.System.putInt(getContentResolver(),
                         android.provider.Settings.System.SCREEN_BRIGHTNESS, 192);


                    }

It worked properly for me

Ann
  • 797
  • 1
  • 7
  • 18
1

You need to create the variable:

private WindowManager.LayoutParams mParams;

then override this method (to save your previous params):

@Override
public void onWindowAttributesChanged(WindowManager.LayoutParams params) {
    mParams = params;
    super.onWindowAttributesChanged(params);
}

than where you wish to change the screen brightness (on the app) just use:

    mParams.screenBrightness = 0.01f; //use a value between 0.01f for low brightness and 1f for high brightness
    getWindow().setAttributes(mParams);

tested on api version 28.

Tal Fiskus
  • 11
  • 2
0

Was just looking into this for Android 10 and this still works for me on there. But requires getting the calling Activity instance inside the fragment which is less than optimal since we only get the context from onAttach now. Setting it to -1.0f sets it to the system value (the one from brightness settings slider), 0.0f to 1.0f sets brightness values from min to max at your leisure.

    WindowManager.LayoutParams lp = myactivity.getWindow().getAttributes();
    lp.screenBrightness = brightness;
    myactivity.getWindow().setAttributes(lp);
    myactivity.getWindow().addFlags(WindowManager.LayoutParams.FLAGS_CHANGED);
draekko
  • 121
  • 2
  • 5
0

I'm using this utils class works for Android 9

public class BrightnessUtil {

public static final int BRIGHTNESS_DEFAULT = 190;
public static final int BRIGHTNESS_MAX = 225;
public static final int BRIGHTNESS_MIN = 0;

public static boolean checkForSettingsPermission(Activity activity) {
    if (isNotAllowedWriteSettings(activity)) {
        startActivityToAllowWriteSettings(activity);
        return false;
    }
    return true;
}

public static void stopAutoBrightness(Activity activity) {

    if (!isNotAllowedWriteSettings(activity)) {
        Settings.System.putInt(activity.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
    }

}

public static void setBrightness(Activity activity, int brightness) {

    if (!isNotAllowedWriteSettings(activity)) {
        //constrain the value of brightness
        if (brightness < BRIGHTNESS_MIN)
            brightness = BRIGHTNESS_MIN;
        else if (brightness > BRIGHTNESS_MAX)
            brightness = BRIGHTNESS_MAX;


        ContentResolver cResolver = activity.getContentResolver();
        Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
    }
}

private static void startActivityToAllowWriteSettings(Activity activity) {
    Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
    intent.setData(Uri.parse("package:" + activity.getPackageName()));
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    activity.startActivity(intent);
}

@SuppressLint("ObsoleteSdkInt")
private static boolean isNotAllowedWriteSettings(Activity activity) {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.System.canWrite(activity);
}

}

Cube
  • 116
  • 5