1

I have the same need like this, but I found the answer under that question aren't work.

I want to make buttons to change my screen brightness while my app is running.

I have found this code, but it doesn't work if I copy this code into my mainActivity directly.

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

I use android studio and API level is 21 and I added user permission.

This piece code is the nearest to my target, who can help me run this code?

Community
  • 1
  • 1
Peter Zhu
  • 1,154
  • 3
  • 15
  • 27

3 Answers3

2

This worked for me:

In onCreate() method write this,

private int brightness;

try{
    Settings.System.putInt(getContentResolver(),
                           Settings.System.SCREEN_BRIGHTNESS_MODE,
                           Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);

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

To update the brightness,

Settings.System.putInt(getContentResolver(), System.SCREEN_BRIGHTNESS, brightness);
LayoutParams layoutpars = getWindow().getAttributes();
layoutpars.screenBrightness = brightness / (float)255;
getWindow().setAttributes(layoutpars);

Permission in manifest,

<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>
Fran Marzoa
  • 4,293
  • 1
  • 37
  • 53
Apurva
  • 7,871
  • 7
  • 40
  • 59
  • 1
    Note that as of api 23 that developers need to ask user's permission explicitly to access system settings https://stackoverflow.com/questions/50959842/android-permission-write-settings-cant-use-in-manifest – Paul Apr 11 '19 at 20:43
0

If you read that question carefully you'll find that you need to refresh your activity and one possible solution to refresh your activity (as mentioned in that answer too) is to create a dummy activity, start it and that finish in in its onCreate() method. you also need this permission in your manifest:

 <uses-permission android:name="android.permission.WRITE_SETTINGS" />
Milad Faridnia
  • 9,113
  • 13
  • 65
  • 78
  • 1
    Note that as of api 23 that developers need to ask user's permission explicitly to access system settings https://stackoverflow.com/questions/50959842/android-permission-write-settings-cant-use-in-manifest – Paul Apr 11 '19 at 20:44
0

Window#mWindowAttributes screenBrightness 0 to 1 adjusts the brightness from dark to full bright