0 前言
Android-P可通过“Developer options > Night mode”打开夜间模式,本文研究其配置和效果。
验证环境:Pixel 3a、模拟器
1 设置
上图对应XML配置如下:
<ListPreference
android:key="dark_ui_mode"
android:title="@string/dark_ui_mode"
android:dialogTitle="@string/dark_ui_mode_title"
android:entries="@array/dark_ui_mode_entries"
android:entryValues="@array/dark_ui_mode_values" />
<!-- @file: packages/apps/Settings/res/xml/development_settings.xml -->
上图对应XML配置如下:
<!-- Titles for ui dark mode preference. -->
<string-array name="dark_ui_mode_entries" >
<item>Automatic (based on time of day)</item>
<item>Always on</item>
<item>Always off</item>
</string-array>
<!-- Values for ui dark mode preference. -->
<string-array name="dark_ui_mode_values" translatable="false" >
<item>auto</item>
<item>yes</item>
<item>no</item>
</string-array>
<!-- @file: packages/apps/Settings/res/values/arrays.xml -->
对应代码如下:
packages/apps/Settings/src/com/android/settings/development/DarkUIPreferenceController.java
frameworks/base/core/java/android/app/UiModeManager.java
frameworks/base/core/java/android/app/IUiModeManager.aidl
frameworks/base/services/core/java/com/android/server/UiModeManagerService.java
从下面函数来看,需要“MODIFY_DAY_NIGHT_MODE”权限才能设置夜间模式:
@Override
public void setNightMode(int mode) {
if (isNightModeLocked() && (getContext().checkCallingOrSelfPermission(
android.Manifest.permission.MODIFY_DAY_NIGHT_MODE)
!= PackageManager.PERMISSION_GRANTED)) {
Slog.e(TAG, "Night mode locked, requires MODIFY_DAY_NIGHT_MODE permission");
return;
}
...
}
// @file: frameworks/base/services/core/java/com/android/server/UiModeManagerService.java
设置结果保存到如下字段中:
public static final String UI_NIGHT_MODE = "ui_night_mode";
// @file: frameworks/base/core/java/android/provider/Settings.java
可通过下面命令查看当前设置:
adb shell settings get secure ui_night_mode
# 0 - Automatic (based on time of day)
# 1 - Always on
# 2 - Always off
2 实现
TODO
参考资料
[1]Android P 开启和关闭夜间模式以及调节浓度的方法
[2]android 夜间模式
[3]简洁优雅地实现夜间模式
[4]Android夜间模式 - DayNight Mode的使用
[5]日夜切换两种模式
[6]Android中夜间模式的三种实现方式
[7]Android日间模式夜间模式切换(无需重启)