How to change screen brightness programmatically in `Fragment`

Viewed 2596

I need to set the brightness screen to max level when a Dialog Fragment shows in my application. My application has minimum support of Android SDK 23 and I tried to set the brightness inside onCreate() of my Dialog Fragment like this:

WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
float brightness=1.0f;
lp.screenBrightness = brightness;
getActivity().getWindow().setAttributes(lp);

But the brightness screen only changes for a few moments. How can I set the brightness screen to maximum level when dialog was opened and reset it again when fragment dialog was closed?

1 Answers

Try below code

 //add below permission in your manifest file
  <uses-permission android:name="android.permission.WRITE_SETTINGS" />

// also ask setting permission at runtime
  if(Build.VERSION.SDK_INT>Build.VERSION_CODES.M) {
       boolean canWriteSettings = Settings.System.canWrite(this);
        if (!canWriteSettings) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
            startActivity(intent);
        }
    }


  //  finally use below method for set brightness
      public void setScreenBrightness(Context mContext,int brightnessValue){
    // Make sure brightness value between 0 to 255
    if(brightnessValue >= 0 && brightnessValue <= 255){
        Settings.System.putInt(
                mContext.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS,
                brightnessValue
        );
    }
}
Related