Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 夜間模式最佳實踐:三種方案與源碼級解析

編輯:關於 Android 程式設計

Android 系統設定裡並沒有「夜間模式」這個選項,對於習慣睡前滑手機的使用者,只能靠手動調低螢幕亮度稍微改善體驗。如今越來越多應用把夜間模式做進自家 App,說不定哪天 Google 也會把這功能放進系統。

業界實現夜間模式主要有兩種主流方案,各有利弊,而我更推崇第三種:

  1. 透過切換 theme 實現夜間模式。
  2. 透過資源 id 映射實現夜間模式。
  3. 透過修改 uiMode 切換夜間模式。

需要說明的是,以上幾種方案都把資源內嵌在 Apk 中;像新浪微博那種需要下載資源包的方案不在本文討論範圍。

方案一:切換 Theme

首先在 attrs.xml 中,為需要隨 theme 變化的內容定義屬性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="textColor" format="color|reference" />
    <attr name="mainBackground" format="color|reference" />
</resources>

接著在不同 theme 中給這些屬性設不同的值:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 預設 -->
    <style name="ThemeDefault" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="mainBackground">#ffffff</item>
        <item name="textColor">#000000</item>
    </style>
    <!-- 夜間 -->
    <style name="ThemeNight" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="mainBackground">#000000</item>
        <item name="textColor">#ffffff</item>
    </style>
</resources>

佈局檔中透過 ?attr/屬性名 取得當前 theme 對應的值:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/main_screen"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="?attr/mainBackground">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="改變 Theme"
        android:onClick="changeTheme"
        android:textColor="?attr/textColor" />
</LinearLayout>

在 Activity 中切換:

public void changeTheme() {
    if (isNightMode) {
        setTheme(R.style.ThemeDefault);
        isNightMode = false;
    } else {
        setTheme(R.style.ThemeNight);
        isNightMode = true;
    }
    setContentView(R.layout.activity_main);
}

其中 isNightMode 是標記當前是否夜間模式的全域變數;設定完 theme 後,需要呼叫 restartActivity 或 setContentView 重新刷新 UI。

包括 Google 自家在內的許多應用都採用這種方式,這大體也是官方推薦做法。但它有兩個明顯不足:規模較大的應用需要隨 theme 變化的屬性非常多,都得逐一定義,相當繁瑣;另外新 theme 生效通常要 restartActivity,切換時畫面會閃一下。

想避開閃爍,可以只更新需要變化的部分:

private void updateTheme() {
    TypedValue typedValue = new TypedValue();
    Resources.Theme theme = getTheme();
    theme.resolveAttribute(R.attr.textColor, typedValue, true);
    findViewById(R.id.button).setBackgroundColor(typedValue.data);
    theme.resolveAttribute(R.attr.mainBackground, typedValue, true);
    findViewById(R.id.main_screen).setBackgroundColor(typedValue.data);
}

代價是要為每個需要變色的 View 寫一段更新邏輯。

方案二:資源 id 映射

核心思路很直接:取得資源前,先把日間模式的 resId 換成夜間模式對應的 id,再交給 Resources 讀取。

public static Drawable getDrawable(Context context, int id) {
    return context.getResources().getDrawable(getResId(id));
}

public static int getResId(int defaultResId) {
    if (!isNightMode()) {
        return defaultResId;
    }
    if (sResourceMap == null) {
        buildResourceMap();
    }
    int themedResId = sResourceMap.get(defaultResId);
    return themedResId == 0 ? defaultResId : themedResId;
}

映射表用 SparseIntArray 建立日與夜的一一對應:

private static void buildResourceMap() {
    sResourceMap = new SparseIntArray();
    sResourceMap.put(R.drawable.common_background, R.drawable.common_background_night);
    // ...
}

這個方案簡單粗暴,麻煩之處與方案一類似:每新增一或多組資源都得補一條映射,UI 刷新方式也差不多。目前一些主流新聞閱讀類應用(如今日頭條、網易新聞)採用的正是這種做法。

方案三:修改 uiMode(推薦)

先把取得資源的地方統一收斂到 Application 的 Resources,在 Application 的 onCreate 中初始化:

public static void init(Context context) {
    sRes = context.getResources();
}

切換夜間模式時,透過更新 uiMode 來更新 Resources 的配置,系統就會依 uiMode 讀取 night 目錄下的資源;同時在 res 中為夜間資源加上 -night 後綴,例如 values-night、drawable-night。

public static void updateNightMode(boolean on) {
    DisplayMetrics dm = sRes.getDisplayMetrics();
    Configuration config = sRes.getConfiguration();
    config.uiMode &= ~Configuration.UI_MODE_NIGHT_MASK;
    config.uiMode |= on ? Configuration.UI_MODE_NIGHT_YES : Configuration.UI_MODE_NIGHT_NO;
    sRes.updateConfiguration(config, dm);
}

關於 Android 的資源查找機制,可以參考老羅的《Android 應用程序資源的查找過程》一文,看系統是如何精準定位資源的。這種方案最大的好處是新增資源極其直觀——只要按後綴放進對應目錄即可,無需維護任何映射表;不足之處在於 UI 更新仍做不到非常順滑的無縫切換。

我是怎麼找到第三種方案的

在 Android 開發文件中搜尋 night,會看到這段描述:

night: Night time
notnight: Day time
Added in API level 8.

This can change during the life of your application if night mode is left in auto mode (default), in which case the mode changes based on the time of day. You can enable or disable this mode using UiModeManager. See Handling Runtime Changes for information about how this affects your application during runtime.

也就是說,官方原本設計的是透過 UiModeManager 來控制:

/**
 * Sets the night mode. Changes to the night mode are only effective when
 * the car or desk mode is enabled on a device.
 *
 * The mode can be one of:
 * {@link #MODE_NIGHT_NO} - sets the device into notnight mode.
 * {@link #MODE_NIGHT_YES} - sets the device into night mode.
 * {@link #MODE_NIGHT_AUTO} - automatic night/notnight switching
 * depending on the location and certain other sensors.
 */
public void setNightMode(int mode)

不幸的是,這個方法只在駕駛模式或桌上底座模式下才生效。那先開啟駕駛模式再設定呢?實務上不可行——駕駛模式會改變系統 UI,副作用太大。

於是一路往下讀源碼。UiModeManagerService.java 的 setNightMode 中:

if (isDoingNightModeLocked() && mNightMode != mode) {
    Settings.Secure.putInt(getContext().getContentResolver(),
            Settings.Secure.UI_NIGHT_MODE, mode);
    mNightMode = mode;
    updateLocked(0, 0);
}

boolean isDoingNightModeLocked() {
    return mCarModeEnabled || mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED;
}

isDoingNightModeLocked 判斷了 DockState 與 mCarMode 狀態;條件滿足時,實際上只改了 mNightMode 的值。繼續跟蹤 updateLocked,會發現 updateConfigurationLocked 中更新了 Configuration 的 uiMode。

再看 Configuration 中 uiMode 的說明:

/**
 * Bit mask of the ui mode. Currently there are two fields:
 * The {@link #UI_MODE_TYPE_MASK} bits define the overall ui mode of the
 * device. They may be one of {@link #UI_MODE_TYPE_UNDEFINED},
 * {@link #UI_MODE_TYPE_NORMAL}, {@link #UI_MODE_TYPE_DESK},
 * {@link #UI_MODE_TYPE_CAR}, {@link #UI_MODE_TYPE_TELEVISION},
 * {@link #UI_MODE_TYPE_APPLIANCE}, or {@link #UI_MODE_TYPE_WATCH}.
 *
 * The {@link #UI_MODE_NIGHT_MASK} defines whether the screen
 * is in a special mode. They may be one of {@link #UI_MODE_NIGHT_UNDEFINED},
 * {@link #UI_MODE_NIGHT_NO} or {@link #UI_MODE_NIGHT_YES}.
 */
public int uiMode;

uiMode 是 public 的,可以直接設定。既然 UiModeManager 最終也不過是改 Configuration 的 uiMode,那我們為什麼不直接改?答案是:真的可以,而且只需要上面那一小段程式碼。但若沒有讀過 UiModeManager 的實作,大概很難想到如此簡潔的路徑。

三種方案的取捨

方案一最貼近官方推薦、心智負擔最低,適合頁面結構簡單的應用;方案二在已有大量圖文資源的內容型 App 中很常見,改造成本可控;方案三資源組織最清爽、擴展成本最低,特別適合介面層級多、色彩定義龐大的中大型專案,代價是需要自行處理切換時的畫面刷新。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved