Android : 螢幕亮度的調整

weixin_33860722發表於2016-11-15

關於螢幕亮度的調整可以從以下幾個方面入手:

  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個方法配合使用即可 .

相關文章