How to change brightness programmatically on the Android app screen as well as reflect it on the System level.
Image credit: Pixel 4a Quick Settings (Joe Maring) |
Change brightness without Permissions
screenBrightness
attribute of the window, like so
val layout: WindowManager.LayoutParams? = activity?.window?.attributes layout?.screenBrightness = 0.9f activity?.window?.attributes = layout
screenBrightness
attribute is a floating-point value ranging
from 0 to 1, where 0.0 is 0% brightness, 0.5 is 50% brightness, and 1.0 is
100% brightness.
Let’s take a look at the example below:
Change brightness with Permissions
Image credit: Material Design |
The first step would be to add WRITE_SETTINGS
permission in
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_SETTINGS" tools:ignore="ProtectedPermissions"/>
WRITE_SETTINGS
is a protected setting that requests the user to
allow writing System settings. If you want to know more about permissions, read
Android Runtime Permissions
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); } }
The next step is to set the brightness for the app. This time we’ll just pass the value to the system and let the system handle the brightness of the device instead of setting it manually.
Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightness);
brightness
value should be in the range of 0–255
.
So, if you have a slider with a range (0-max) then you can normalize the value
in the 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 the range of the slider value (0–100%) to
0–255
like this
float brightness = normalize(progress, 0, 100, 0.0f, 255.0f);