Android : 屏幕亮度的调整

关于屏幕亮度的调整可以从以下几个方面入手:

  1. 判断是否开启了自动亮度调节
public static boolean isAutoBrightness(ContentResolver aContentResolver) {
    boolean automicBrightness = false;    
    try{        
        automicBrightness = Settings.System.getInt(aContentResolver,                
        Settings.System.SCREEN_BRIGHTNESS_MODE) ==Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
    } catch(SettingNotFoundException e) {
        e.printStackTrace();
    }    
    return automicBrightness;
    }
  1. **获取屏幕的亮度 **
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;
}
  1. **设置亮度 **
public static void setBrightness(Activity activity, int brightness) {   
     // Settings.System.putInt(activity.getContentResolver(),    
    // Settings.System.SCREEN_BRIGHTNESS_MODE,    
    // Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);    
    WindowManager.LayoutParams lp = activity.getWindow().getAttributes();   
    lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);  
    Log.d("lxy", "set  lp.screenBrightness == " + lp.screenBrightness);
     activity.getWindow().setAttributes(lp); 
 }
  1. 停止自动亮度调节
public static void stopAutoBrightness(Activity activity) {   
    Settings.System.putInt(activity.getContentResolver(), 
Settings.System.SCREEN_BRIGHTNESS_MODE,  Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
}
  1. 开启亮度自动调节
public static void startAutoBrightness(Activity activity) {   
    Settings.System.putInt(activity.getContentResolver(),
 Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
}
  1. 保存亮度设置状态
public static void saveBrightness(ContentResolver resolver, int brightness) {    
    Uri uri = android.provider.Settings.System.getUriFor("screen_brightness");   
    android.provider.Settings.System.putInt(resolver, "screen_brightness", brightness);    
    // resolver.registerContentObserver(uri, true, myContentObserver);
    resolver.notifyChange(uri, null);
}
  1. 最后
      如果只在自己的activity显示期间调节亮度 , 那就直接设置亮度(3)并且关闭自动亮度调节(4) , 当该Activity退出后应该恢复自动亮度调节(5) ;
      如果想直接对手机进行设置 , 那设置亮度(3)后 , 应该保存亮度设置状态(6) ;
      以上6个方法配合使用即可 .
    原文作者:筱南独舞
    原文地址: https://www.jianshu.com/p/678e12c5d38a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞