小米的新版系统(大于MIUI9),取到的当前亮度值是远大于255的,应该是小米修改了系统亮度的最大值(不知道小米是出于什么原因修改的)。所以最大值要根据系统版本动态获取。
public static final int MAX_BRIGHTNESS_VALUE = 230; //设置的最大亮度值
/**
* 判断是否开启了自动亮度调节
*
* @param context
* @return
*/
public static boolean IsAutoBrightness(Context context) {
boolean IsAutoBrightness = false;
try {
IsAutoBrightness = Settings.System.getInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
return IsAutoBrightness;
}
/**
* 获取当前系统屏幕的亮度
*
* @param context
* @return
*/
public static int getScreenBrightness(Context context) {
int nowBrightnessValue = 0;
ContentResolver resolver = context.getContentResolver();
try {
nowBrightnessValue = android.provider.Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS);
} catch (Exception e) {
e.printStackTrace();
}
return nowBrightnessValue;
}
/**
* 设置亮度,程序退出之后亮度失效
*
* @param context
* @param brightness
*/
public static void setCurrentWindowBrightness(Context context, int brightness) {
// 如果开启自动亮度,则关闭。否则,设置了亮度值也是无效的
if (IsAutoBrightness(context)) {
stopAutoBrightness(context);
}
// context转换为Activity
Activity activity = (Activity) context;
WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
// 异常处理
if (brightness < 1) {
brightness = 1;
}
// 异常处理
if (brightness > getBrightnessMax()) {
brightness = getBrightnessMax();
}
if(brightness==MAX_BRIGHTNESS_VALUE){
lp.screenBrightness = brightness/255f;
}else {
lp.screenBrightness = brightness * (1f / getBrightnessMax());
}
activity.getWindow().setAttributes(lp);
}
/**
* 获取最大亮度
* @return max
*/
private static int getBrightnessMax() {
try {
Resources system = Resources.getSystem();
int resId = system.getIdentifier("config_screenBrightnessSettingMaximum", "integer", "android");
if (resId != 0) {
return system.getInteger(resId);
}
}catch (Exception ignore){
}
return 255;
}
// 停止自动亮度调节
public static void stopAutoBrightness(Context context) {
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}
// 开启亮度自动调节
public static void startAutoBrightness(Context context) {
Settings.System.putInt(context.getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
}