Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android調節屏幕亮度工具類BrightnessUtils

Android調節屏幕亮度工具類BrightnessUtils

編輯:關於Android編程

 

 

項目需要做了一個調節屏幕的工具類

/*
 * Android調節屏幕亮度工具類
 * by itas109
 * http://blog.csdn.net/itas109
 * 
 * 注意:需要添加setting權限
 * 
 */
public class BrightnessUtils {

	// 判斷是否開啟了自動亮度調節

	public static boolean IsAutoBrightness(Context context) {

		boolean IsAutoBrightness = false;

		try {

			IsAutoBrightness = Settings.System.getInt(
					context.getContentResolver(),

					Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;

		}

		catch (SettingNotFoundException e)

		{

			e.printStackTrace();

		}

		return IsAutoBrightness;
	}

	// 獲取當前屏幕的亮度

	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;
	}

	// 設置亮度
	// 程序退出之後亮度失效

	public static void setCurWindowBrightness(Context context, int brightness) {

		// 如果開啟自動亮度,則關閉。否則,設置了亮度值也是無效的
		if (IsAutoBrightness(context)) {
			stopAutoBrightness(context);
		}

		// context轉換為Activity
		Activity activity = (Activity) context;
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();

		// 異常處理
		if (brightness < 1) {
			brightness = 1;
		}

		// 異常處理
		if (brightness > 255) {
			brightness = 255;
		}

		lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);

		activity.getWindow().setAttributes(lp);

	}

	// 設置系統亮度
	// 程序退出之後亮度依舊有效
	public static void setSystemBrightness(Context context, int brightness) {
		// 異常處理
		if (brightness < 1) {
			brightness = 1;
		}

		// 異常處理
		if (brightness > 255) {
			brightness = 255;
		}
		saveBrightness(context, brightness);
	}

	// 停止自動亮度調節

	public static void stopAutoBrightness(Context context) {

		Settings.System.putInt(context.getContentResolver(),

		Settings.System.SCREEN_BRIGHTNESS_MODE,

		Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
	}

	// 開啟亮度自動調節

	public static void startAutoBrightness(Context context) {

		Settings.System.putInt(context.getContentResolver(),

		Settings.System.SCREEN_BRIGHTNESS_MODE,

		Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);

	}

	// 保存亮度設置狀態

	public static void saveBrightness(Context context, int brightness) {

		Uri uri = android.provider.Settings.System
				.getUriFor(screen_brightness);

		android.provider.Settings.System.putInt(context.getContentResolver(),
				screen_brightness, brightness);

		context.getContentResolver().notifyChange(uri, null);
	}

}


運行效果圖

\

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved