Android自動切換夜間主題
媽耶,網上搜怎麼實現自動切換夜間主題都沒資料的,全是夜間主題的實現,只能自己想辦法了。
最終解決的方案倒是很簡單,不過走了很多彎路。腦子不是很好使了。
線索就是,應用會在任何時候啟動,它該怎麼確定自己是在某個時間(進入夜間或到了白天)之後第一次被啟動。為了知道這個狀態,就要記住上一次啟動的時間,跟現在的時間比較。同時當然要有夜間模式的起始時間和結束時間。這樣用四個時間來實現自動切換夜間主題。
// 現在的時間 val now = System.currentTimeMillis() // 上次啟動的時間 val lastStartTime = prefs.getLong(keyLastStartTime, now) // 儲存好這次的啟動時間,用於下一次使用 editor.putLong(keyLastStartTime, now).apply() // 只有在自動切換開啟時才進入邏輯 if (isAutoNightEnabled()) { // 獲取自動切換的起始時間和結束時間 val span = getNightSpan() // 將四個毫秒值轉換為Date,方便之後的比較 val lastDate = Date(lastStartTime) val nowDate = Date() val startDate = span.startTimeDate() val endDate = span.endTimeDate() // 獲取現在是否是夜間模式,省去重複切換 val isNightEnabled = isNightThemeEnabled if (lastDate.before(startDate) && nowDate.after(startDate) && !isNightEnabled) { // 進入夜間 // 當且僅當,上一次啟動時間是在夜間開始之前,並且現在時間是在夜間開始時候,同時夜間模式沒有被開啟 configureNightTheme(true) restartWithFading(intent(this, showAutoNightMsg = true)) } else if (lastDate.before(endDate) && nowDate.after(endDate) && isNightEnabled) { // 進入夜間 // 當且僅當,上一次啟動時間是在白天開始之前,並且現在時間是在白天開始時候,同時夜間模式已被開啟 configureNightTheme(false) restartWithFading(intent(this, showAutoNightMsg = true)) } } // 通過在Intent中放Boolean,顯示一個撤銷按鈕 if (intent.getBooleanExtra(EXTRA_SHOW_AUTO_NIGHT_MSG, false)) { if (isNightThemeEnabled) { rootLayout.longSnackbar(R.string.auto_night_to_night_done, R.string.action_undo) { configureNightTheme(false) restartWithFading(intent(this)) } } else { rootLayout.longSnackbar(R.string.auto_night_to_day_done, R.string.action_undo) { configureNightTheme(true) restartWithFading(intent(this)) } } }
獲取自動切換夜間模式時的方法,這裡一定要確保秒和毫秒為0。
fun startTimeDate(): Date = Calendar.getInstance().apply { set(Calendar.HOUR_OF_DAY, startHour) set(Calendar.MINUTE, startMinute) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) }.time
還有什麼更好的實現方法嗎?