Android调节屏幕亮度实现代码

调节屏幕亮度时,先设置当前activity亮度,再并保存为系统亮度即可。

1 onCreate()里检查系统亮度并设置seekBar:

     private void screenBrightness_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 (SettingNotFoundException e)
          {
              // TODO Auto-generated catch block
              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亮度,并保存为系统亮度:
        

//屏幕亮度
     private void setScreenBritness(int brightness)
     {
          //不让屏幕全暗
          if(brightness<=1)
          {
              brightness=1;
          }
          //设置当前activity的屏幕亮度
          WindowManager.LayoutParams lp = 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
//        Uri uri = 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);
     }

代码技巧

转载请关注公众号:代码技巧 回复:授权

本文链接地址:https://www.oudahe.com/p/49714/