记录一下Android系统设置亮度遇到的坑


本文重在记录自己写系统亮度调节时遇到的坑。

参考博客:http://www.2cto.com/kf/201509/439791.html

一、获取系统亮度

public static int getSystemScreenBrightness(Activity activity) {
		try {
			return Settings.System.getInt(activity.getContentResolver(),
					Settings.System.SCREEN_BRIGHTNESS);
		} catch (SettingNotFoundException e) {
			e.printStackTrace();
		}
		return 0;
	}
二、判断是否设置自动亮度调节

public static boolean isAutoBrightness(Activity activity) {
		try {
			int autoBrightness = Settings.System.getInt(
					activity.getContentResolver(),
					Settings.System.SCREEN_BRIGHTNESS_MODE);
			if (autoBrightness == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
				return true;
			}
		} catch (SettingNotFoundException e) {
			e.printStackTrace();
		}
		return false;
	}
三、设置当前屏幕亮度并保存
public static void setScreenBritness(Activity activity, int brightness) {
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		if (brightness == -1) {
			lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
		} else {
			if (brightness < 10) {
				brightness = 10;
			}
			lp.screenBrightness = Float.valueOf(brightness / 255f);
			Settings.System.putInt(activity.getContentResolver(),
					Settings.System.SCREEN_BRIGHTNESS, brightness);
		}
		activity.getWindow().setAttributes(lp);
	}
四、关闭系统自动亮度调节
public static void closeAutoBrightness(Activity activity) {
		Settings.System.putInt(activity.getContentResolver(),
				Settings.System.SCREEN_BRIGHTNESS_MODE,
				Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
	}
五、打开系统自动亮度调节
public static void openAutoBrightness(Activity activity) {
		setScreenBritness(activity, -1);
		Settings.System.putInt(activity.getContentResolver(),
				Settings.System.SCREEN_BRIGHTNESS_MODE,
				Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
	}

重点是第三点和第五点,当打开系统自动亮度调节的时候,需要将当前activity的亮度设置为自动获取亮度状态,即
setScreenBritness(activity, -1);
否则看不到亮度的变化值。




你可能感兴趣的:(Android系统,android)