1. 程式人生 > >Android亮度調整解析

Android亮度調整解析

乾貨總結,Android亮度調整有一下一些知識點需要注意:

1、Android亮度調整,包括調整系統亮度和調整指定Activity亮度。

2、Android系統亮度模式有兩種,自動模式和手動模式。

3、自動模式下和手動模式下獲取系統亮度值的方式不一樣,具體請看程式碼(謝謝老大指點,差點以為沒辦法獲取自動模式下的亮度)。

4、系統亮度值的區間為[0, 255]。需要注意的是,自動亮度模式下,直接獲取到的系統亮度值區間為[-1,1]。

5、這一點可能很多人沒注意,調整過Activity亮度之後,系統亮度調整在當前Activity中會失效。

6、系統亮度變化值,可以通過監聽系統屬性值變化獲得,具體看程式碼。

7、Android 6.0 及以上系統,對系統變數相關操作,需要硬編碼動態申請許可權。

8、動態監聽系統亮度變化,注意防止記憶體洩露。

好了,乾貨,請看程式碼,看程式碼,看程式碼

一、工具類BrightnessUtils

public class BrightnessUtils {private static final String TAG = BrightnessUtils.class.getSimpleName();
    /**
     * 判斷是否開啟了自動亮度調節
     */
public static boolean isAutoBrightness(Activity activity) {
        boolean 
automicBrightness = false; try { automicBrightness = Settings.System.getInt(activity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE) == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC; } catch (Settings.SettingNotFoundException e){ e.printStackTrace(); } return
automicBrightness; } /** * 獲取螢幕的亮度 */ 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; if(isAutoBrightness(activity)){ return getAutoScreenBrightness(activity); }else{ return getManualScreenBrightness(activity); } } /** * 獲取手動模式下的螢幕亮度 */ public static int getManualScreenBrightness(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; } /** * 獲取自動模式下的螢幕亮度 */ public static int getAutoScreenBrightness(Activity activity) { float nowBrightnessValue = 0; ContentResolver resolver = activity.getContentResolver(); try { nowBrightnessValue = android.provider.Settings.System.getFloat(resolver, "screen_auto_brightness_adj"); //[-1,1],無法直接獲取到Setting中的值,以字串表示 Log.d(TAG, "[ouyangyj] Original AutoBrightness Value:" + nowBrightnessValue); } catch (Exception e) { e.printStackTrace(); } float tempBrightness = nowBrightnessValue + 1.0f; //[0,2] float fValue = (tempBrightness/2.0f)*225.0f; Log.d(TAG,"[ouyangyj] Converted Value: " + fValue); return (int)fValue; } /** * 設定亮度 */ public static void setBrightness(Activity activity, int brightness) { // Settings.System.putInt(activity.getContentResolver(), // Settings.System.SCREEN_BRIGHTNESS_MODE, // Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); try{ WindowManager.LayoutParams lp = activity.getWindow().getAttributes(); lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f); MLog.debug(TAG, "set lp.screenBrightness == " + lp.screenBrightness); activity.getWindow().setAttributes(lp); }catch(Exception ex){ ex.printStackTrace(); } } /** * 停止自動亮度調節 */ public static void stopAutoBrightness(Activity activity) { try{ Settings.System.putInt(activity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); }catch (Exception ex) { ex.printStackTrace(); } } /**0 * 開啟亮度自動調節 * @param activity */ public static void startAutoBrightness(Activity activity) { try{ Settings.System.putInt(activity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC); }catch (Exception ex){ ex.printStackTrace(); } } /** * 儲存亮度設定狀態 */ public static void saveBrightness(Activity activity, int brightness) { try{ Uri uri = android.provider.Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS); android.provider.Settings.System.putInt(activity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brightness); // resolver.registerContentObserver(uri, true, myContentObserver); activity.getContentResolver().notifyChange(uri, null); }catch(Exception ex){ ex.printStackTrace(); } } }

二、監聽亮度變化

@Override
protected void onStart() {
    super.onStart();
    registerOberver();
    MLog.info(TAG, "onStart");
}
@Override
protected void onStop() {
    super.onStop();
    unregisterOberver();
    MLog.info(TAG, "onStop");
}
private final Uri BRIGHTNESS_MODE_URI =
            Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS_MODE);
    private final Uri BRIGHTNESS_URI =
            Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
    private final Uri BRIGHTNESS_ADJ_URI =
            Settings.System.getUriFor("screen_auto_brightness_adj");//Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ);
private boolean isRegistered = false;

    private void registerOberver() {
        try {
            if (BrightnessObserver != null) {
                if (!isRegistered) {
                    MLog.debug(TAG, "[ouyangyj] register BrightnessObserver");
                    final ContentResolver cr = getContentResolver();
                    cr.unregisterContentObserver(BrightnessObserver);
                    cr.registerContentObserver(BRIGHTNESS_MODE_URI, false, BrightnessObserver);
                    cr.registerContentObserver(BRIGHTNESS_URI, false, BrightnessObserver);
                    cr.registerContentObserver(BRIGHTNESS_ADJ_URI, false, BrightnessObserver);
                    isRegistered = true;
                }
            }
        } catch (Throwable throwable) {
            MLog.debug(TAG, "[ouyangyj] register BrightnessObserver error! " + throwable);
        }
    }

    private void unregisterOberver() {
        try {
            if (BrightnessObserver != null) {
                if (isRegistered) {
                    MLog.debug(TAG, "[ouyangyj] unregister BrightnessObserver");
                    getContentResolver().unregisterContentObserver(BrightnessObserver);
                    isRegistered = false;
                }
            }
        } catch (Throwable throwable) {
            MLog.debug(TAG, "[ouyangyj] unregister BrightnessObserver error! " + throwable);
        }
    }

    private ContentObserver BrightnessObserver = new ContentObserver(new Handler()) {
        @Override
public void onChange(boolean selfChange) {
           onChange(selfChange, null);
        }

        @Override
public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange);
            if (selfChange) return;
            MLog.debug(TAG, "[ouyangyj] BrightnessObserver onChange");
            if (BRIGHTNESS_MODE_URI.equals(uri)) {
                MLog.debug(this, "[ouyangyj] 亮度模式改變");
//                updateBrightnessInfo();
} else if (BRIGHTNESS_URI.equals(uri) && !BrightnessUtils.isAutoBrightness(BasicChannelTemplateActivity.this)) {
                MLog.debug(this, "[ouyangyj] 亮度模式為手動模式 值改變");
//                updateBrightnessInfo();
} else if (BRIGHTNESS_ADJ_URI.equals(uri) && BrightnessUtils.isAutoBrightness(BasicChannelTemplateActivity.this)) {
                MLog.debug(this, "[ouyangyj] 亮度模式為自動模式 值改變");
//                updateBrightnessInfo();
} else {
                MLog.debug(this, "[ouyangyj] 亮度調整 其他");
//                updateBrightnessInfo();
}
        }
    };

三、動態授權申請

對應異常

java.lang.SecurityException: balabalabala was not granted  this permission: android.permission.WRITE_SETTINGS.     at android.os.Parcel.readException(Parcel.java:1602)     at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)     at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)     at android.content.ContentProviderProxy.call(ContentProviderNative.java:646)     at android.provider.Settings$NameValueCache.putStringForUser(Settings.java:1325)     at android.provider.Settings$System.putStringForUser(Settings.java:1678)     at android.provider.Settings$System.putIntForUser(Settings.java:1783)     at android.provider.Settings$System.putInt(Settings.java:1777) 文件說明:  Android6.0動態許可權申請參考 貌似很多try catch, 因為真的可能拋異常......

好了,下班了,客官慢走......把建議和意見留下......