Android调节屏幕亮度实现代码
调节屏幕亮度时,先设置当前activity亮度,再并保存为系统亮度即可。
1onCreate()里检查系统亮度并设置seekBar:
privatevoidscreenBrightness_check() { //先关闭系统的亮度自动调节 try { if(android.provider.Settings.System.getInt(getContentResolver(),android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE)==android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { android.provider.Settings.System.putInt(getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE, android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); } } catch(SettingNotFoundExceptione) { //TODOAuto-generatedcatchblock e.printStackTrace(); } //获取当前亮度,获取失败则返回255 intScreenBrightness=(int)(android.provider.Settings.System.getInt(getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS, 255)); //文本、进度条显示 mSeekBar_light.setProgress(intScreenBrightness); mTextView_light.setText(""+intScreenBrightness*100/255); }
2拖动seekBar时设置当前activity亮度,并保存为系统亮度:
//屏幕亮度 privatevoidsetScreenBritness(intbrightness) { //不让屏幕全暗 if(brightness<=1) { brightness=1; } //设置当前activity的屏幕亮度 WindowManager.LayoutParamslp=this.getWindow().getAttributes(); //0到1,调整亮度暗到全亮 lp.screenBrightness=Float.valueOf(brightness/255f); this.getWindow().setAttributes(lp); //保存为系统亮度方法1 android.provider.Settings.System.putInt(getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS, brightness); //保存为系统亮度方法2 //Uriuri=android.provider.Settings.System.getUriFor("screen_brightness"); //android.provider.Settings.System.putInt(getContentResolver(),"screen_brightness",brightness); ////resolver.registerContentObserver(uri,true,myContentObserver); //getContentResolver().notifyChange(uri,null); //更改亮度文本显示 mTextView_light.setText(""+brightness*100/255); }