How to get the brightness percentage in Android?

Viewed 113

I am trying to get the brightness value from Android (12) and converting it to percentage using

android.provider.Settings.System.getInt(context.getContentResolver().SCREEN_BRIGHTNESS)

Now, when brightness is at 0% brightness value is at 1.0 and at 100% brightness value is at 255.0. However, when the brightness is at 50%, the value returned is 22.0. This makes me think the brightness value is logarithmic.

Is there a method to convert this or get this value as percentage?

1 Answers

I have found an approximate solution. Unfortunately, there is no direct way to get access to the linear brightness values through an API in Android.

However, there is a way to approximate it. Note that this issue occurs on devices past Android 9 using a logarithmic brightness curve (Pixel devices for example).

To get the approximate brightness value:

  1. Get the brightness with

android.provider.Settings.System.getFloat(context.getContentResolver().SCREEN_BRIGHTNESS)

  1. Copy the Mathutils file used in the android source code into your project directory

  2. Copy the convertLinearToGammaFloat() function found in AOSP source code here into your class and pass the parameters into it. val will be the brightness value you got from the first step, min will be 0.0f, max will be 255.0f (in case of Pixel devices).

  3. Copy the getPercentage() function from AOSP source code here. Pass in the value got from convertLinearToGammaFLoat() into value.min and max will be the GAMMA_SPACE_MIN and GAMMA_SPACE_MAX variables found here

The value received from getPercentage() will be the approximate brightness percentage value. There is around 3% margin of error for this which you can account for by subtracting it from the total brightness if it is within a certain range.

Related