如何检测 android 上的屏幕亮度范围?

How do I detect the screen brightness range on android?

我正在使用以下代码设置屏幕亮度,这在大多数手机上都能正常工作:

    protected fun setBrightness(value: Float) {
        //Set the system brightness using the brightness variable value
        Settings.System.putInt(contentResolver, Settings.System
            .SCREEN_BRIGHTNESS, (value * 255).toInt())
        //Get the current window attributes
        val layoutpars = window.getAttributes()
        //Set the brightness of this window
        layoutpars.screenBrightness = value
        //Apply attribute changes to this window
        window.setAttributes(layoutpars)
    }

当我传递一个值 1(表示最大值)时,它会转换为 255,据说这是设置屏幕亮度的最大值。但是,在小米 Mi8 上将值设置为 255 不会将亮度设置为全范围,如以下屏幕截图所示:

打印一些调试值并进行实验后,看起来小米 8 的最大亮度值实际上是 1024(或者至少,将该值乘以 1 设置完整的亮度条)。

似乎不​​同的 android 设备可能具有不同的亮度等级。是否有一些 API 可以获得亮度的最大值所以我不需要硬编码不同的常量?

部分小米设备专用。例如小米红米 Note 7 有 0-4000 范围。

官方文档定义SCREEN_BRIGHTNESS范围为0-255。所以,我认为没有API来获得亮度的最大值。

在一些(不是所有)设备上有一个文件“/sys/class/leds/lcd-backlight/max_brightness”可以包含最大值。

而不是将 255 设置为最大值。我更喜欢使用这种方式将亮度设置为最大。只是将 1F 传递给屏幕亮度。

WindowManager.LayoutParams layout = getWindow().getAttributes();
layout.screenBrightness = 1F;
getWindow().setAttributes(layout);

它在不同的 android 设备上运行良好。

使用此方法获取亮度的最大值

public int getMaxBrightness(Context context, int defaultValue){

    PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    if(powerManager != null) {
        Field[] fields = powerManager.getClass().getDeclaredFields();
        for (Field field: fields) {

            //https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/os/PowerManager.java

            if(field.getName().equals("BRIGHTNESS_ON")) {
                field.setAccessible(true);
                try {
                    return (int) field.get(powerManager);
                } catch (IllegalAccessException e) {
                    return defaultValue;
                }
            }
        }
    }
    return defaultValue;
}

我已经在几台设备上测试过(主要是 android 9、10 台设备,包括一些小米设备,它们通常将亮度设置为高于通常的 255),看起来这是可行的。

Google does not promote accessing hidden fields/methods using reflection. Any android update could potentially break this solution.

另一种可能的解决方案 是使用反射访问 PowerManager class 中的 getMaximumScreenBrightnessSetting() 方法。但我没有测试过,因此无法确认结果。

NB :如果您使用此值设置亮度百分比,请记住这一点:从 android 9 开始,亮度设置为 logarithmically .因此设置亮度百分比可能看起来不像亮度滑块中显示的百分比(较低的百分比可能看起来高于亮度滑块上的设置值),但物理亮度将设置正确。