通過程式碼調節Android螢幕亮度
阿新 • • 發佈:2018-11-01
轉載自:https://www.jb51.net/article/136383.html
1、宣告需要的許可權
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
2、判斷是否開啟了自動亮度調節
public static boolean isAutoBrightness(Context context) { ContentResolver resolver = context.getContentResolver(); boolean automicBrightness = false; try { automicBrightness = Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC; } catch (Settings.SettingNotFoundException e) { e.printStackTrace(); } return automicBrightness; }
3、獲取當前螢幕亮度
public static int getScreenBrightness(Context context) { int nowBrightnessValue = 0; ContentResolver resolver = context.getContentResolver(); try { nowBrightnessValue = android.provider.Settings.System.getInt(resolver, Settings.System.SCREEN_BRIGHTNESS); } catch (Exception e) { e.printStackTrace(); } return nowBrightnessValue; }
4、關閉自動亮度調節
public static boolean autoBrightness(Context activity, boolean flag) { int value = 0; if (flag) { value = Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC; //開啟 } else { value = Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;//關閉 } return Settings.System.putInt(activity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, value); }
5、設定亮度,退出app也能保持該亮度值
public static void saveBrightness(Context context, int brightness) {
ContentResolver resolver = context.getContentResolver();
Uri uri = android.provider.Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
android.provider.Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
resolver.notifyChange(uri, null);
}
6、設定當前activity顯示的亮度
public static void setBrightness(Activity activity, int brightness) {
WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
activity.getWindow().setAttributes(lp);
}