Reputation: 1194
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?
Upvotes: 1
Views: 13355
Reputation: 11
Window#mWindowAttributes screenBrightness 0 to 1 adjusts the brightness from dark to full bright
Upvotes: 1
Reputation: 7911
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>
Upvotes: 3
Reputation: 9477
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" />
Upvotes: 0