在oncreat函数添加注册监听函数,当监听到系统亮度改变时,就保存当前的屏幕亮度值,并使之生效 ,注意只对手动调节屏幕亮度生效;当手机系统亮度为自动调节时是没法控制的
private void monitorBright(){try{this.getContentResolver().registerContentObserver(Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS),true, BrightnessMode);}catch (Exception e){e.printStackTrace();}}private ContentObserver BrightnessMode = new ContentObserver(new Handler()) {@Overridepublic void onChange(boolean selfChange) {super.onChange(selfChange);try{int status = BrightnessTools.getBrightnessMode(PlayerActivity.this.getContentResolver());DebugUtils.printInfo(TAG, "系统亮度status:" + status);if (status == 0) {// 状态为:0表示系统亮度为手动修改int systemBrightness = BrightnessTools.getScreenBrightness(VideoPlayerActivity.this);DebugUtils.printInfo(TAG, "监听系统亮度:" + systemBrightness);WindowManager.LayoutParams lp = getWindow().getAttributes();float b = systemBrightness * 1f / 255;DebugUtils.debug(TAG, "系统亮度转换成屏幕亮度:" + b);//亮度是从0~1中的一个浮点数lp.screenBrightness = Math.min(Math.max(b, 0.01f), 1);// Set BrightnessgetWindow().setAttributes(lp);} else {// 表示系统亮度为自动调节(不做处理)}}catch (Exception e){e.printStackTrace();}}};public static int getBrightnessMode(ContentResolver aContentResolver){int screenMode=0;try{screenMode =Settings.System.getInt(aContentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE);} catch (Exception localException){}return screenMode;}/** * 获取屏幕的亮度 */ public static int getScreenBrightness(Activity activity) {int nowBrightnessValue = 0;ContentResolver resolver = activity.getContentResolver();try{nowBrightnessValue = android.provider.Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS); }catch(Exception e) { e.printStackTrace(); }return nowBrightnessValue; }
//在ondestroy函数取消注册监听
this.getContentResolver().unregisterContentObserver(BrightnessMode);
下面与系统亮度调整改变屏幕亮度无关,下面是进入页面将系统亮度初始化为屏幕亮度,以便于后面调节亮度时初始值不为0
保存当前的屏幕亮度值,并使之生效
//将系统亮度转初始化成屏幕亮度,避免后面调节时从0开始int systemBrightness = BrightnessTools.getScreenBrightness(this);DebugUtils.debug(TAG, "系统亮度:" + systemBrightness);WindowManager.LayoutParams lp = getWindow().getAttributes();float b = systemBrightness * 1f / 255;DebugUtils.printInfo(TAG, "系统亮度转换成屏幕亮度:" + b);//亮度是从0~1中的一个浮点数lp.screenBrightness = Math.min(Math.max(b, 0.01f), 1);// Set BrightnessgetWindow().setAttributes(lp);
如果觉得《android 系统亮度调整改变屏幕亮度(只对手动调节屏幕亮度生效)》对你有帮助,请点赞、收藏,并留下你的观点哦!