业务上需要调节界面亮度,方便二维码扫描,记录一下。
系统的亮度值默认区间是0-255,调节亮度有以下两种
- 当前界面亮度
- 系统亮度
调节当前界面亮度
退出当前界面时,亮度自动调节模式继续生效。
/**
* 设置当前界面亮度值
*
* @param activity
* @param aimBrightness
*/
public static void setCurrentScreenBrightness(Activity activity, @IntRange(from = 0, to = 255) int aimBrightness) {
WindowManager.LayoutParams layoutParams = activity.getWindow().getAttributes();
layoutParams.screenBrightness = Float.valueOf(aimBrightness / 255.0f);
activity.getWindow().setAttributes(layoutParams);
}
调节系统亮度
调节系统亮度时需要申请WRITE_SETTINGS权限( 注意6.0以后的权限申请)
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
注意:只有为手动调节模式时,才能动态设置系统的亮度,所以需要提前对亮度模式进行操作,再进行亮度调节。
通过Activity中的getContentResolver()方法得到ContentResolver实例,实现对系统的ContentProver的数据访问。
Settings.System.SCREEN_BRIGHTNESS_MODE
获取当前屏幕亮度调节模式,其中
-
SCREEN_BRIGHTNESS_MODE_AUTOMATIC = 1
表示自动调节模式 -
SCREEN_BRIGHTNESS_MODE_MANUAL = 0
表示手动调节模式
/**
* 设置系统亮度
*
* @param activity
* @param aimBrightness
*/
public static void setSystemBrightness(Activity activity, @IntRange(from = 0, to = 255) int aimBrightness) {
setToManualBrightness(activity);
Uri uri = Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
ContentResolver resolver = activity.getContentResolver();
Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, aimBrightness);
activity.getContentResolver().notifyChange(uri, null);
}
/**
* 设置为手动模式
*
* @return
*/
public static void setToManualBrightness(@NonNull Context context) {
ContentResolver resolver = context.getContentResolver();
try {
int brightMode = Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS_MODE);
if (brightMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
//设置为手动调节模式
Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
}
其他
通过 Settings.System.SCREEN_BRIGHTNESS
获取当前屏幕亮度
/**
* 获取当前界面亮度值
*
* @param context
* @return
*/
public static int getCurrentScreenBrightness(@NonNull Context context) {
ContentResolver resolver = context.getContentResolver();
int currentBrightness = 0;
try {
currentBrightness = Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
return currentBrightness;
}