games: opt-in daily reminder for the daily puzzle (#568)
- Commit
31eb367614a7a66b9e0af3d056c539ada1939d15- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-23 15:24 UTC (3 months ago)
- Parents
18006eb
Diff
games/pipes/build.gradle.kts
diff --git a/games/pipes/build.gradle.kts b/games/pipes/build.gradle.ktsindex f6559c9362..8a49e40093 100644--- a/games/pipes/build.gradle.kts+++ b/games/pipes/build.gradle.kts@@ -17,4 +17,5 @@ android { dependencies { implementation(project(":sdk:games"))+ implementation(project(":library:work")) }
games/pipes/src/main/AndroidManifest.xml
diff --git a/games/pipes/src/main/AndroidManifest.xml b/games/pipes/src/main/AndroidManifest.xmlindex 8fa4ea33c4..a70a432237 100644--- a/games/pipes/src/main/AndroidManifest.xml+++ b/games/pipes/src/main/AndroidManifest.xml@@ -3,6 +3,7 @@ <uses-permission android:name="com.vayunmathur.games.hub.permission.READ_GAME_DATA" /> <uses-permission android:name="com.vayunmathur.games.hub.permission.WRITE_GAME_DATA" />+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <application android:allowBackup="true"
games/pipes/src/main/java/com/vayunmathur/games/pipes/Navigation.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/Navigation.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/Navigation.ktindex b471a5aa91..bc72250992 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/Navigation.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/Navigation.kt@@ -12,7 +12,7 @@ import com.vayunmathur.games.pipes.ui.DailyLevelScreen import com.vayunmathur.games.pipes.ui.GameScreen import com.vayunmathur.games.pipes.ui.LevelScreen import com.vayunmathur.games.pipes.ui.PackScreen-import com.vayunmathur.games.pipes.ui.SettingsScreen+import com.vayunmathur.games.pipes.ui.SettingsPage import com.vayunmathur.library.ui.AchievementNotification import com.vayunmathur.library.ui.GameCenterScreen import com.vayunmathur.library.util.GameHubComposeHook@@ -34,7 +34,7 @@ fun Navigation(viewModel: PipesViewModel) { entry<Route.DailySelector> { DailyLevelScreen(backStack, viewModel) } entry<Route.DailyGame> { GameScreen(backStack, viewModel, PipesViewModel.DAILY_PACK_INDEX, it.levelIndex) } entry<Route.GameCenter> { GameCenterScreen(backupAgent = AppBackupAgent(), manager = viewModel.achievementsManager, onBack = { backStack.pop() }) }- entry<Route.Settings> { SettingsScreen(backStack, viewModel) }+ entry<Route.Settings> { SettingsPage(backStack, viewModel) } } newAchievement?.let { AchievementNotification(it) { viewModel.dismissAchievementNotification() } } }
games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesUiContract.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesUiContract.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesUiContract.ktindex 476f170f57..cb0047f3e1 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesUiContract.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesUiContract.kt@@ -58,8 +58,26 @@ interface PipesActions { fun commitDraw() {} fun onUndo() {} fun onRestart() {}- companion object { val Noop: PipesActions = object : PipesActions {} } }++/** What the settings screen draws. */+data class SettingsUiState(+ val colorblind: Boolean = false,+ val reminderEnabled: Boolean = false,+ val reminderHour: Int = 20,+ val reminderMinute: Int = 0,+)++/** Settings callbacks. Same no-op-default arrangement as [PipesActions]. */+interface SettingsActions {+ fun setColorblind(enabled: Boolean) {}+ fun setReminderEnabled(enabled: Boolean) {}+ fun setReminderTime(hour: Int, minute: Int) {}++ companion object {+ val Noop: SettingsActions = object : SettingsActions {}+ }+}
games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.ktindex b370cd5604..249a5ce2f2 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/platform/PipesViewModel.kt@@ -12,6 +12,8 @@ import com.vayunmathur.library.util.LevelStats import com.vayunmathur.library.util.AchievementsManager import com.vayunmathur.library.util.DailyChallengeStore import com.vayunmathur.library.util.DailyStreakReporter+import com.vayunmathur.library.work.DailyPuzzleReminder+import com.vayunmathur.library.work.DailyReminderSettings import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.util.LevelStatsRepository import kotlinx.coroutines.Dispatchers@@ -70,7 +72,7 @@ class PipesViewModel(application: Application) : AndroidViewModel(application), */ private val dailyRepository = LevelStatsRepository(application, "daily_stats") - private val dailyStore = DailyChallengeStore(application, "pipes_daily")+ private val dailyStore = DailyChallengeStore(application, DAILY_KEY_PREFIX) private val _dailyDay = MutableStateFlow(dailyStore.todayEpochDay()) val dailyDay: StateFlow<Long> = _dailyDay.asStateFlow()@@ -98,6 +100,40 @@ class PipesViewModel(application: Application) : AndroidViewModel(application), viewModelScope.launch { ds.setBoolean(KEY_COLORBLIND, value) } } + private val reminderSettings = DailyReminderSettings(application, DAILY_KEY_PREFIX)++ val reminderEnabled: StateFlow<Boolean> = reminderSettings.enabled+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)++ val reminderMinutesOfDay: StateFlow<Long> = reminderSettings.minutesOfDay+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), DailyPuzzleReminder.DEFAULT_MINUTES_OF_DAY)++ fun setReminderEnabled(enabled: Boolean) {+ viewModelScope.launch {+ reminderSettings.setEnabled(enabled)+ rescheduleReminder(enabled, reminderMinutesOfDay.value)+ }+ }++ fun setReminderTime(hour: Int, minute: Int) {+ viewModelScope.launch {+ val minutes = (hour * 60 + minute).toLong()+ reminderSettings.setMinutesOfDay(minutes)+ rescheduleReminder(reminderEnabled.value, minutes)+ }+ }++ private fun rescheduleReminder(enabled: Boolean, minutesOfDay: Long) {+ DailyPuzzleReminder.update(+ context = getApplication(),+ keyPrefix = DAILY_KEY_PREFIX,+ notificationId = REMINDER_NOTIFICATION_ID,+ enabled = enabled,+ hour = (minutesOfDay / 60).toInt(),+ minute = (minutesOfDay % 60).toInt(),+ )+ }+ init { viewModelScope.launch { achievementsManager.checkExistingAchievements()@@ -405,6 +441,11 @@ class PipesViewModel(application: Application) : AndroidViewModel(application), companion object { const val KEY_COLORBLIND = "pipes_colorblind" + /** Namespace shared by the daily-challenge store and its reminder. */+ const val DAILY_KEY_PREFIX = "pipes_daily"++ private const val REMINDER_NOTIFICATION_ID = 5102+ /** Sentinel [PipesUiState.packIndex] for the date-generated daily pack. */ const val DAILY_PACK_INDEX = -2
games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/SettingsScreen.kt
diff --git a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/SettingsScreen.kt b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/SettingsScreen.ktindex 1ed850a423..9a46679952 100644--- a/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/SettingsScreen.kt+++ b/games/pipes/src/main/java/com/vayunmathur/games/pipes/ui/SettingsScreen.kt@@ -1,37 +1,82 @@ package com.vayunmathur.games.pipes.ui--import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding+import android.Manifest+import android.os.Build import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource-import androidx.compose.ui.unit.dp import com.vayunmathur.games.pipes.R import com.vayunmathur.games.pipes.Route import com.vayunmathur.games.pipes.platform.PipesViewModel+import com.vayunmathur.games.pipes.platform.SettingsActions+import com.vayunmathur.games.pipes.platform.SettingsUiState+import com.vayunmathur.library.ui.DailyReminderSettingsSection import com.vayunmathur.library.ui.DetailScaffold import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Switch-import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.SettingsSwitchRow import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.rememberPermissionRequest import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.ui.R as UiR -@OptIn(ExperimentalMaterial3Api::class)+/** Binds [PipesViewModel] to the stateless [SettingsScreen]. */ @Composable-fun SettingsScreen(backStack: NavBackStack<Route>, viewModel: PipesViewModel) {+fun SettingsPage(backStack: NavBackStack<Route>, viewModel: PipesViewModel) { val colorblind by viewModel.colorblind.collectAsState()- DetailScaffold(title = stringResource(UiR.string.settings), backStack = backStack, scrollBehavior = appBarScrollBehavior()) {- Row(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {- Column(Modifier.weight(1f)) { Text(stringResource(R.string.colorblind_mode), style = MaterialTheme.typography.titleMedium); Text(stringResource(R.string.colorblind_mode_desc), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)) }- Switch(checked = colorblind, onCheckedChange = { viewModel.setColorblind(it) })+ val reminderEnabled by viewModel.reminderEnabled.collectAsState()+ val reminderMinutes by viewModel.reminderMinutesOfDay.collectAsState()++ val requestNotifications = rememberPermissionRequest(Manifest.permission.POST_NOTIFICATIONS)++ SettingsScreen(+ state = SettingsUiState(+ colorblind = colorblind,+ reminderEnabled = reminderEnabled,+ reminderHour = (reminderMinutes / 60).toInt(),+ reminderMinute = (reminderMinutes % 60).toInt(),+ ),+ actions = object : SettingsActions {+ override fun setColorblind(enabled: Boolean) = viewModel.setColorblind(enabled)++ override fun setReminderEnabled(enabled: Boolean) {+ // Asked for lazily, on opt-in only, so the screen never blocks on a prompt.+ if (enabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ requestNotifications()+ }+ viewModel.setReminderEnabled(enabled)+ }++ override fun setReminderTime(hour: Int, minute: Int) =+ viewModel.setReminderTime(hour, minute)+ },+ onBack = { backStack.pop() },+ )+}++/** The settings screen, ViewModel-free so a preview can render it. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun SettingsScreen(state: SettingsUiState, actions: SettingsActions, onBack: () -> Unit) {+ DetailScaffold(+ title = stringResource(UiR.string.settings),+ onNavigateBack = onBack,+ scrollBehavior = appBarScrollBehavior(),+ ) {+ SettingsSection {+ SettingsSwitchRow(+ title = stringResource(R.string.colorblind_mode),+ supportingText = stringResource(R.string.colorblind_mode_desc),+ checked = state.colorblind,+ onCheckedChange = { actions.setColorblind(it) },+ ) }+ DailyReminderSettingsSection(+ enabled = state.reminderEnabled,+ hour = state.reminderHour,+ minute = state.reminderMinute,+ onEnabledChange = { actions.setReminderEnabled(it) },+ onTimeChange = { hour, minute -> actions.setReminderTime(hour, minute) },+ ) } }
games/unblockjam/build.gradle.kts
diff --git a/games/unblockjam/build.gradle.kts b/games/unblockjam/build.gradle.ktsindex d8d38f941e..c19a0ef8cd 100644--- a/games/unblockjam/build.gradle.kts+++ b/games/unblockjam/build.gradle.kts@@ -17,4 +17,5 @@ android { dependencies { implementation(project(":sdk:games"))+ implementation(project(":library:work")) }
games/unblockjam/src/main/AndroidManifest.xml
diff --git a/games/unblockjam/src/main/AndroidManifest.xml b/games/unblockjam/src/main/AndroidManifest.xmlindex 3a07c31311..d54c35bce7 100644--- a/games/unblockjam/src/main/AndroidManifest.xml+++ b/games/unblockjam/src/main/AndroidManifest.xml@@ -3,6 +3,7 @@ <uses-permission android:name="com.vayunmathur.games.hub.permission.READ_GAME_DATA" /> <uses-permission android:name="com.vayunmathur.games.hub.permission.WRITE_GAME_DATA" />+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <application android:allowBackup="true"@@ -20,9 +21,12 @@ android:theme="@style/Theme.General"> <intent-filter> <action android:name="android.intent.action.MAIN" />- <category android:name="android.intent.category.LAUNCHER" /> </intent-filter>+ <intent-filter>+ <action android:name="android.intent.action.APPLICATION_PREFERENCES" />+ <category android:name="android.intent.category.DEFAULT" />+ </intent-filter> </activity> </application>
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/Navigation.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/Navigation.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/Navigation.ktindex d2c3d39e3c..7f25d3f8bc 100644--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/Navigation.kt+++ b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/Navigation.kt@@ -1,5 +1,7 @@ package com.vayunmathur.games.unblockjam +import android.Manifest+import android.os.Build import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background@@ -48,6 +50,8 @@ import com.vayunmathur.games.unblockjam.platform.AppBackupAgent import com.vayunmathur.games.unblockjam.platform.DailyProgress import com.vayunmathur.games.unblockjam.platform.GameActions import com.vayunmathur.games.unblockjam.platform.GameUiState+import com.vayunmathur.games.unblockjam.platform.SettingsActions+import com.vayunmathur.games.unblockjam.platform.SettingsUiState import com.vayunmathur.games.unblockjam.platform.UnblockJamViewModel import com.vayunmathur.games.unblockjam.platform.blockDragGestures import com.vayunmathur.games.unblockjam.ui.UnblockJamTheme@@ -56,21 +60,26 @@ import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CardDefaults import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.DailyReminderSettingsSection+import com.vayunmathur.library.ui.DetailScaffold import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.GameCenterScreen import com.vayunmathur.library.ui.Icon import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconCheck+import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.ui.IconStar import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.rememberPermissionRequest import com.vayunmathur.library.util.GameHubComposeHook import com.vayunmathur.library.util.LevelStats import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.openSettingsIfRequested import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.library.ui.R as UiR import java.time.LocalDate@@ -80,6 +89,7 @@ import java.time.format.FormatStyle @Composable fun Navigation(viewModel: UnblockJamViewModel) { val backStack = rememberNavBackStack<Route>(Route.PackSelector)+ backStack.openSettingsIfRequested(Route.Settings) val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState() GameHubComposeHook("unblockjam", viewModel.achievementsManager)@@ -87,7 +97,12 @@ fun Navigation(viewModel: UnblockJamViewModel) { Box(Modifier.fillMaxSize()) { MainNavigation(backStack) { entry<Route.PackSelector> {- PackPage(backStack, viewModel, onOpenGameCenter = { backStack.add(Route.GameCenter) })+ PackPage(+ backStack,+ viewModel,+ onOpenGameCenter = { backStack.add(Route.GameCenter) },+ onOpenSettings = { backStack.add(Route.Settings) },+ ) } entry<Route.LevelSelector> { val pack = LevelPack.PACKS[it.packIndex]@@ -114,6 +129,9 @@ fun Navigation(viewModel: UnblockJamViewModel) { onBack = { backStack.pop() } ) }+ entry<Route.Settings> {+ SettingsPage(viewModel, onBack = { backStack.pop() })+ } } newAchievement?.let {@@ -125,7 +143,12 @@ fun Navigation(viewModel: UnblockJamViewModel) { } /** Binds [UnblockJamViewModel] to the stateless [PackScreen]. */ @Composable-fun PackPage(backStack: NavBackStack<Route>, viewModel: UnblockJamViewModel, onOpenGameCenter: () -> Unit) {+fun PackPage(+ backStack: NavBackStack<Route>,+ viewModel: UnblockJamViewModel,+ onOpenGameCenter: () -> Unit,+ onOpenSettings: () -> Unit,+) { val dailyCompleted by viewModel.dailyCompleted.collectAsState() val dailyDay by viewModel.dailyDay.collectAsState() val dailyStreak by viewModel.dailyStreak.collectAsState()@@ -141,9 +164,59 @@ fun PackPage(backStack: NavBackStack<Route>, viewModel: UnblockJamViewModel, onO onOpenPack = { backStack.add(Route.LevelSelector(it)) }, onOpenDaily = { backStack.add(Route.DailySelector) }, onOpenGameCenter = onOpenGameCenter,+ onOpenSettings = onOpenSettings, ) } +/** Binds [UnblockJamViewModel] to the stateless [SettingsScreen]. */+@Composable+fun SettingsPage(viewModel: UnblockJamViewModel, onBack: () -> Unit) {+ val reminderEnabled by viewModel.reminderEnabled.collectAsState()+ val reminderMinutes by viewModel.reminderMinutesOfDay.collectAsState()++ val requestNotifications = rememberPermissionRequest(Manifest.permission.POST_NOTIFICATIONS)++ SettingsScreen(+ state = SettingsUiState(+ reminderEnabled = reminderEnabled,+ reminderHour = (reminderMinutes / 60).toInt(),+ reminderMinute = (reminderMinutes % 60).toInt(),+ ),+ actions = object : SettingsActions {+ override fun setReminderEnabled(enabled: Boolean) {+ // Asked for lazily, on opt-in only, so the screen never blocks on a prompt.+ if (enabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ requestNotifications()+ }+ viewModel.setReminderEnabled(enabled)+ }++ override fun setReminderTime(hour: Int, minute: Int) =+ viewModel.setReminderTime(hour, minute)+ },+ onBack = onBack,+ )+}++/** The settings screen, ViewModel-free so a preview can render it. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun SettingsScreen(state: SettingsUiState, actions: SettingsActions, onBack: () -> Unit) {+ DetailScaffold(+ title = stringResource(UiR.string.settings),+ onNavigateBack = onBack,+ scrollBehavior = appBarScrollBehavior(),+ ) {+ DailyReminderSettingsSection(+ enabled = state.reminderEnabled,+ hour = state.reminderHour,+ minute = state.reminderMinute,+ onEnabledChange = { actions.setReminderEnabled(it) },+ onTimeChange = { hour, minute -> actions.setReminderTime(hour, minute) },+ )+ }+}+ @OptIn(ExperimentalMaterial3Api::class) @Composable fun PackScreen(@@ -152,10 +225,14 @@ fun PackScreen( onOpenGameCenter: () -> Unit, daily: DailyProgress? = null, onOpenDaily: () -> Unit = {},+ onOpenSettings: () -> Unit = {}, ) { AppScaffold( title = stringResource(R.string.pack_selector), actions = {+ IconButton(onClick = onOpenSettings) {+ IconSettings()+ } IconButton(onClick = onOpenGameCenter) { Icon(painterResource(id = android.R.drawable.btn_star_big_on), "Achievements") }
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/Route.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/Route.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/Route.ktindex 90ecf0771a..1226b4813f 100644--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/Route.kt+++ b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/Route.kt@@ -17,4 +17,6 @@ sealed interface Route : NavKey { data class DailyGame(val levelIndex: Int) : Route @Serializable data object GameCenter : Route+ @Serializable+ data object Settings : Route }\ No newline at end of file
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/GameUiContract.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/GameUiContract.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/GameUiContract.ktindex 0151e8b645..21ac41eab4 100644--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/GameUiContract.kt+++ b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/GameUiContract.kt@@ -55,3 +55,20 @@ interface GameActions { val Noop: GameActions = object : GameActions {} } }++/** What the settings screen draws. */+data class SettingsUiState(+ val reminderEnabled: Boolean = false,+ val reminderHour: Int = 20,+ val reminderMinute: Int = 0,+)++/** Settings callbacks. Same no-op-default arrangement as [GameActions]. */+interface SettingsActions {+ fun setReminderEnabled(enabled: Boolean) {}+ fun setReminderTime(hour: Int, minute: Int) {}++ companion object {+ val Noop: SettingsActions = object : SettingsActions {}+ }+}
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.ktindex b4fbdb99ac..533731d945 100644--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.kt+++ b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.kt@@ -11,6 +11,8 @@ import com.vayunmathur.library.util.LevelStats import com.vayunmathur.library.util.AchievementsManager import com.vayunmathur.library.util.DailyChallengeStore import com.vayunmathur.library.util.DailyStreakReporter+import com.vayunmathur.library.work.DailyPuzzleReminder+import com.vayunmathur.library.work.DailyReminderSettings import com.vayunmathur.library.util.LevelStatsRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow@@ -76,7 +78,41 @@ class UnblockJamViewModel(application: Application) : AndroidViewModel(applicati */ private val dailyRepository = LevelStatsRepository(application, "daily_stats") - private val dailyStore = DailyChallengeStore(application, "unblockjam_daily")+ private val dailyStore = DailyChallengeStore(application, DAILY_KEY_PREFIX)++ private val reminderSettings = DailyReminderSettings(application, DAILY_KEY_PREFIX)++ val reminderEnabled: StateFlow<Boolean> = reminderSettings.enabled+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)++ val reminderMinutesOfDay: StateFlow<Long> = reminderSettings.minutesOfDay+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), DailyPuzzleReminder.DEFAULT_MINUTES_OF_DAY)++ fun setReminderEnabled(enabled: Boolean) {+ viewModelScope.launch {+ reminderSettings.setEnabled(enabled)+ rescheduleReminder(enabled, reminderMinutesOfDay.value)+ }+ }++ fun setReminderTime(hour: Int, minute: Int) {+ viewModelScope.launch {+ val minutes = (hour * 60 + minute).toLong()+ reminderSettings.setMinutesOfDay(minutes)+ rescheduleReminder(reminderEnabled.value, minutes)+ }+ }++ private fun rescheduleReminder(enabled: Boolean, minutesOfDay: Long) {+ DailyPuzzleReminder.update(+ context = getApplication(),+ keyPrefix = DAILY_KEY_PREFIX,+ notificationId = REMINDER_NOTIFICATION_ID,+ enabled = enabled,+ hour = (minutesOfDay / 60).toInt(),+ minute = (minutesOfDay % 60).toInt(),+ )+ } private val _dailyDay = MutableStateFlow(dailyStore.todayEpochDay()) val dailyDay: StateFlow<Long> = _dailyDay.asStateFlow()@@ -286,6 +322,11 @@ class UnblockJamViewModel(application: Application) : AndroidViewModel(applicati } companion object {+ /** Namespace shared by the daily-challenge store and its reminder. */+ const val DAILY_KEY_PREFIX = "unblockjam_daily"++ private const val REMINDER_NOTIFICATION_ID = 5103+ /** Sentinel [UnblockJamUiState.packIndex] for the date-generated daily pack. */ const val DAILY_PACK_INDEX = -2
games/wordmaker/build.gradle.kts
diff --git a/games/wordmaker/build.gradle.kts b/games/wordmaker/build.gradle.ktsindex 685d78f527..89e3d5f276 100644--- a/games/wordmaker/build.gradle.kts+++ b/games/wordmaker/build.gradle.kts@@ -18,6 +18,7 @@ android { dependencies { implementation(project(":sdk:games"))+ implementation(project(":library:work")) implementation(libs.androidx.datastore.preferences) implementation(libs.brotli.dec) }
games/wordmaker/src/main/AndroidManifest.xml
diff --git a/games/wordmaker/src/main/AndroidManifest.xml b/games/wordmaker/src/main/AndroidManifest.xmlindex f17d712745..a0eea4a481 100644--- a/games/wordmaker/src/main/AndroidManifest.xml+++ b/games/wordmaker/src/main/AndroidManifest.xml@@ -3,6 +3,7 @@ <uses-permission android:name="com.vayunmathur.games.hub.permission.READ_GAME_DATA" /> <uses-permission android:name="com.vayunmathur.games.hub.permission.WRITE_GAME_DATA" />+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <application android:allowBackup="true"
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerUiContract.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerUiContract.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerUiContract.ktindex 3dc5c2e100..b2a089ce36 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerUiContract.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerUiContract.kt@@ -79,3 +79,22 @@ interface CompetitiveLobbyActions { val Noop: CompetitiveLobbyActions = object : CompetitiveLobbyActions {} } }++/** What the settings screen draws. */+data class SettingsUiState(+ val tapToSpell: Boolean = false,+ val reminderEnabled: Boolean = false,+ val reminderHour: Int = 20,+ val reminderMinute: Int = 0,+)++/** Settings callbacks. Same no-op-default arrangement as [WordGameActions]. */+interface SettingsActions {+ fun setTapToSpell(enabled: Boolean) {}+ fun setReminderEnabled(enabled: Boolean) {}+ fun setReminderTime(hour: Int, minute: Int) {}++ companion object {+ val Noop: SettingsActions = object : SettingsActions {}+ }+}
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModel.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModel.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModel.ktindex 0052b9a8a2..8e73011ff7 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModel.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/platform/WordMakerViewModel.kt@@ -13,6 +13,8 @@ import com.vayunmathur.games.wordmaker.domain.CompetitiveLevelGenerator import com.vayunmathur.games.wordmaker.domain.Dictionary import com.vayunmathur.library.util.DailyChallengeStore import com.vayunmathur.library.util.DailyStreakReporter+import com.vayunmathur.library.work.DailyPuzzleReminder+import com.vayunmathur.library.work.DailyReminderSettings import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow@@ -51,6 +53,14 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio val tapToSpell: StateFlow<Boolean> = levelDataStore.tapToSpell .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false) + private val reminderSettings = DailyReminderSettings(application, DAILY_KEY_PREFIX)++ val reminderEnabled: StateFlow<Boolean> = reminderSettings.enabled+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)++ val reminderMinutesOfDay: StateFlow<Long> = reminderSettings.minutesOfDay+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), DailyPuzzleReminder.DEFAULT_MINUTES_OF_DAY)+ private val _hintCooldownEnd = MutableStateFlow(System.currentTimeMillis() + 30_000L) val hintCooldownEnd: StateFlow<Long> = _hintCooldownEnd.asStateFlow() @@ -90,7 +100,7 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio // ---- Daily challenge state ---- - private val dailyStore = DailyChallengeStore(application, "wordmaker_daily")+ private val dailyStore = DailyChallengeStore(application, DAILY_KEY_PREFIX) private val _dailyDay = MutableStateFlow(dailyStore.todayEpochDay()) val dailyDay: StateFlow<Long> = _dailyDay.asStateFlow()@@ -343,6 +353,32 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio viewModelScope.launch { levelDataStore.setTapToSpell(enabled) } } + fun setReminderEnabled(enabled: Boolean) {+ viewModelScope.launch {+ reminderSettings.setEnabled(enabled)+ rescheduleReminder(enabled, reminderMinutesOfDay.value)+ }+ }++ fun setReminderTime(hour: Int, minute: Int) {+ viewModelScope.launch {+ val minutes = (hour * 60 + minute).toLong()+ reminderSettings.setMinutesOfDay(minutes)+ rescheduleReminder(reminderEnabled.value, minutes)+ }+ }++ private fun rescheduleReminder(enabled: Boolean, minutesOfDay: Long) {+ DailyPuzzleReminder.update(+ context = getApplication(),+ keyPrefix = DAILY_KEY_PREFIX,+ notificationId = REMINDER_NOTIFICATION_ID,+ enabled = enabled,+ hour = (minutesOfDay / 60).toInt(),+ minute = (minutesOfDay % 60).toInt(),+ )+ }+ override fun revealHint(crosswordData: CrosswordData, foundWords: Set<String>, revealedHints: Set<Pair<Int, Int>>) { val revealed = foundWords.flatMapTo(mutableSetOf()) { word -> crosswordData.letterPositions[word]?.flatten().orEmpty()@@ -372,6 +408,11 @@ class WordMakerViewModel(application: Application) : AndroidViewModel(applicatio } companion object {+ /** Namespace shared by the daily-challenge store and its reminder. */+ const val DAILY_KEY_PREFIX = "wordmaker_daily"++ private const val REMINDER_NOTIFICATION_ID = 5101+ /** Highest level shipped as a designed asset; higher levels are generated at runtime. */ const val MAX_DESIGNED_LEVEL = 8000
games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/SettingsPage.kt
diff --git a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/SettingsPage.kt b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/SettingsPage.ktindex bae34be851..4ef7c17541 100644--- a/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/SettingsPage.kt+++ b/games/wordmaker/src/main/java/com/vayunmathur/games/wordmaker/ui/SettingsPage.kt@@ -1,57 +1,84 @@ package com.vayunmathur.games.wordmaker.ui--import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding+import android.Manifest+import android.os.Build import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.ui.BackupButtons+import com.vayunmathur.library.ui.DailyReminderSettingsSection import com.vayunmathur.library.ui.DetailScaffold import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.Icon-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Switch-import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.SettingsSwitchRow import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.rememberPermissionRequest import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource-import androidx.compose.ui.unit.dp import com.vayunmathur.games.wordmaker.R+import com.vayunmathur.games.wordmaker.platform.SettingsActions+import com.vayunmathur.games.wordmaker.platform.SettingsUiState import com.vayunmathur.games.wordmaker.platform.WordMakerViewModel -@OptIn(ExperimentalMaterial3Api::class)+/** Binds [WordMakerViewModel] to the stateless [SettingsScreen]. */ @Composable fun SettingsPage(viewModel: WordMakerViewModel, onBack: () -> Unit) { val tapToSpell by viewModel.tapToSpell.collectAsState()+ val reminderEnabled by viewModel.reminderEnabled.collectAsState()+ val reminderMinutes by viewModel.reminderMinutesOfDay.collectAsState()++ val requestNotifications = rememberPermissionRequest(Manifest.permission.POST_NOTIFICATIONS)++ SettingsScreen(+ state = SettingsUiState(+ tapToSpell = tapToSpell,+ reminderEnabled = reminderEnabled,+ reminderHour = (reminderMinutes / 60).toInt(),+ reminderMinute = (reminderMinutes % 60).toInt(),+ ),+ actions = object : SettingsActions {+ override fun setTapToSpell(enabled: Boolean) = viewModel.setTapToSpell(enabled) + override fun setReminderEnabled(enabled: Boolean) {+ // Asked for lazily, on opt-in only, so the screen never blocks on a prompt.+ if (enabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ requestNotifications()+ }+ viewModel.setReminderEnabled(enabled)+ }++ override fun setReminderTime(hour: Int, minute: Int) =+ viewModel.setReminderTime(hour, minute)+ },+ onBack = onBack,+ )+}++/** The settings screen, ViewModel-free so a preview can render it. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun SettingsScreen(state: SettingsUiState, actions: SettingsActions, onBack: () -> Unit) { DetailScaffold( title = stringResource(UiR.string.settings), onNavigateBack = onBack, actions = {- com.vayunmathur.library.ui.BackupButtons(- datastoreNames = listOf("settings")- )+ BackupButtons(datastoreNames = listOf("settings")) }, scrollBehavior = appBarScrollBehavior(), ) {- Row(- modifier = Modifier.fillMaxWidth(),- verticalAlignment = Alignment.CenterVertically- ) {- Column(modifier = Modifier.weight(1f)) {- Text(stringResource(R.string.tap_to_spell), style = com.vayunmathur.library.ui.MaterialTheme.typography.titleMedium)- Text(stringResource(R.string.tap_to_spell_description), style = com.vayunmathur.library.ui.MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)- }- Switch(- checked = tapToSpell,- onCheckedChange = { viewModel.setTapToSpell(it) }+ SettingsSection {+ SettingsSwitchRow(+ title = stringResource(R.string.tap_to_spell),+ supportingText = stringResource(R.string.tap_to_spell_description),+ checked = state.tapToSpell,+ onCheckedChange = { actions.setTapToSpell(it) }, ) }+ DailyReminderSettingsSection(+ enabled = state.reminderEnabled,+ hour = state.reminderHour,+ minute = state.reminderMinute,+ onEnabledChange = { actions.setReminderEnabled(it) },+ onTimeChange = { hour, minute -> actions.setReminderTime(hour, minute) },+ ) } }
library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.ktindex 8f9882a258..5313ae4629 100644--- a/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt+++ b/library/src/main/java/com/vayunmathur/library/util/DataStoreUtils.kt@@ -76,6 +76,11 @@ class DataStoreUtils private constructor(context: Context) { return dataStore.data.first()[booleanPreferencesKey(name)] ?: default } + /** Defaulted variant: unlike [booleanFlow], emits before the key is first written. */+ fun booleanFlow(name: String, default: Boolean): Flow<Boolean> {+ return dataStore.data.map { it[booleanPreferencesKey(name)] ?: default }.distinctUntilChanged()+ }+ suspend fun setBoolean(name: String, value: Boolean) { dataStore.edit { it[booleanPreferencesKey(name)] = value
library/src/main/res/values/strings.xml
diff --git a/library/src/main/res/values/strings.xml b/library/src/main/res/values/strings.xmlindex 53231d3baa..55963df07a 100644--- a/library/src/main/res/values/strings.xml+++ b/library/src/main/res/values/strings.xml@@ -1,4 +1,14 @@ <resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> <!-- Shared library: Core utilities - App name placeholder, required by manifest, not user-visible --> <string name="app_name">App</string>++ <!-- Shared daily-puzzle reminder, used by every game with a daily challenge -->+ <!-- Notification channel name, shown in system notification settings. Noun -->+ <string name="daily_reminder_channel_name">Daily puzzle reminder</string>+ <!-- Notification channel description, shown in system notification settings. Sentence -->+ <string name="daily_reminder_channel_description">A daily nudge when you haven\'t played today\'s puzzle.</string>+ <!-- Reminder notification title. Sentence -->+ <string name="daily_reminder_title">Today\'s puzzle is waiting</string>+ <!-- Reminder notification body. %1$s = app name e.g. Wordmaker. Sentence -->+ <string name="daily_reminder_text">You haven\'t finished today\'s <xliff:g id="app_name" example="Wordmaker">%1$s</xliff:g> puzzle yet.</string> </resources>
library/ui/src/main/java/com/vayunmathur/library/ui/DailyReminderSettingsSection.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/DailyReminderSettingsSection.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/DailyReminderSettingsSection.ktnew file mode 100644index 0000000000..2d90268921--- /dev/null+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/DailyReminderSettingsSection.kt@@ -0,0 +1,62 @@+package com.vayunmathur.library.ui++import androidx.compose.material3.ExperimentalMaterial3Api+import androidx.compose.material3.TimePicker+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.res.stringResource++/**+ * The opt-in daily-puzzle reminder rows: a toggle, and the time it fires.+ *+ * Shared because every daily-puzzle game wants exactly these two rows and the same picker.+ * Knows nothing about scheduling — that is `:library:work`'s `DailyPuzzleReminder`, which this+ * module does not depend on.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun DailyReminderSettingsSection(+ enabled: Boolean,+ hour: Int,+ minute: Int,+ onEnabledChange: (Boolean) -> Unit,+ onTimeChange: (Int, Int) -> Unit,+) {+ var showTimePicker by remember { mutableStateOf(false) }++ SettingsSection(title = stringResource(R.string.settings_reminders)) {+ SettingsSwitchRow(+ title = stringResource(R.string.setting_daily_reminder),+ supportingText = stringResource(R.string.setting_daily_reminder_hint),+ checked = enabled,+ onCheckedChange = onEnabledChange,+ )+ SettingsRow(+ title = stringResource(R.string.setting_daily_reminder_time),+ supportingText = "%02d:%02d".format(hour, minute),+ enabled = enabled,+ onClick = { showTimePicker = true },+ )+ }++ if (showTimePicker) {+ val timeState = rememberTimePickerState(initialHour = hour, initialMinute = minute)+ AlertDialog(+ onDismissRequest = { showTimePicker = false },+ title = { Text(stringResource(R.string.setting_daily_reminder_time)) },+ text = { TimePicker(state = timeState) },+ confirmButton = {+ TextButton(onClick = {+ onTimeChange(timeState.hour, timeState.minute)+ showTimePicker = false+ }) { Text(stringResource(R.string.save)) }+ },+ dismissButton = {+ TextButton(onClick = { showTimePicker = false }) { Text(stringResource(R.string.cancel)) }+ },+ )+ }+}
library/ui/src/main/res/values/strings.xml
diff --git a/library/ui/src/main/res/values/strings.xml b/library/ui/src/main/res/values/strings.xmlindex 0306b6a460..0976af61e3 100644--- a/library/ui/src/main/res/values/strings.xml+++ b/library/ui/src/main/res/values/strings.xml@@ -82,6 +82,15 @@ <string name="clear">Clear</string> <string name="share">Share</string> <string name="undo">Undo</string>+ <!-- Daily-puzzle reminder settings rows, shared by every game with a daily challenge. -->+ <!-- Settings section header. Noun -->+ <string name="settings_reminders">Reminders</string>+ <!-- Settings row: toggle for the opt-in daily reminder. Label -->+ <string name="setting_daily_reminder">Daily puzzle reminder</string>+ <!-- Settings row subtitle explaining when the reminder fires. Sentence -->+ <string name="setting_daily_reminder_hint">Notify me if I haven\'t played today\'s puzzle</string>+ <!-- Settings row: opens a time picker for the reminder. Label -->+ <string name="setting_daily_reminder_time">Reminder time</string> <!-- Shared library: UI – CompassCalibrationBanner: Emphasized title line shown when the magnetometer reports low accuracy --> <string name="compass_low_accuracy_title">Low compass accuracy</string> <!-- Shared library: UI - CompassCalibrationBanner: Instruction line telling the user how to recalibrate the compass -->
library/work/build.gradle.kts
diff --git a/library/work/build.gradle.kts b/library/work/build.gradle.ktsindex 42314a562f..f2d6d122d7 100644--- a/library/work/build.gradle.kts+++ b/library/work/build.gradle.kts@@ -4,4 +4,5 @@ plugins { dependencies { api(libs.androidx.work.runtime.ktx)+ implementation(project(":library")) }
library/work/src/main/java/com/vayunmathur/library/work/DailyPuzzleReminder.kt
diff --git a/library/work/src/main/java/com/vayunmathur/library/work/DailyPuzzleReminder.kt b/library/work/src/main/java/com/vayunmathur/library/work/DailyPuzzleReminder.ktnew file mode 100644index 0000000000..df70597fdc--- /dev/null+++ b/library/work/src/main/java/com/vayunmathur/library/work/DailyPuzzleReminder.kt@@ -0,0 +1,167 @@+package com.vayunmathur.library.work++import android.Manifest+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat+import androidx.core.content.ContextCompat+import androidx.work.CoroutineWorker+import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import androidx.work.workDataOf+import com.vayunmathur.library.R+import com.vayunmathur.library.util.DailyChallengeStore+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.library.util.ensureNotificationChannel+import kotlinx.coroutines.flow.Flow+import java.util.Calendar+import java.util.concurrent.TimeUnit++/**+ * An opt-in daily nudge for a game's daily puzzle, shared by every game that has one.+ *+ * Keyed off the same `keyPrefix` the game gives [DailyChallengeStore], so the worker can read+ * the game's own streak bookkeeping and stay quiet once today's puzzle is done.+ *+ * WorkManager owns the repeat: `PeriodicWorkRequest` reschedules itself, so there is no+ * receiver, no boot receiver and no `AlarmManager` here. Note this is deliberately not+ * [startRepeatedTask], which hardcodes a network constraint and fires immediately — neither+ * suits a nudge that must work offline and only at the chosen time.+ */+object DailyPuzzleReminder {++ const val CHANNEL_ID = "daily_puzzle_reminder"++ /** Default reminder time, 20:00, as minutes since midnight. */+ const val DEFAULT_MINUTES_OF_DAY = 20 * 60L++ private const val KEY_PREFIX = "key_prefix"+ private const val KEY_NOTIFICATION_ID = "notification_id"++ fun update(+ context: Context,+ keyPrefix: String,+ notificationId: Int,+ enabled: Boolean,+ hour: Int,+ minute: Int,+ ) {+ val workManager = WorkManager.getInstance(context)+ val workName = workName(keyPrefix)+ if (!enabled) {+ workManager.cancelUniqueWork(workName)+ return+ }+ val request = PeriodicWorkRequestBuilder<DailyPuzzleReminderWorker>(1, TimeUnit.DAYS)+ .setInitialDelay(initialDelayMinutes(hour, minute), TimeUnit.MINUTES)+ .setInputData(+ workDataOf(+ KEY_PREFIX to keyPrefix,+ KEY_NOTIFICATION_ID to notificationId,+ )+ )+ .build()+ workManager.enqueueUniquePeriodicWork(workName, ExistingPeriodicWorkPolicy.UPDATE, request)+ }++ internal fun keyPrefixOf(data: androidx.work.Data): String? = data.getString(KEY_PREFIX)++ internal fun notificationIdOf(data: androidx.work.Data): Int = data.getInt(KEY_NOTIFICATION_ID, 5100)++ private fun workName(keyPrefix: String) = "${keyPrefix}_reminder"++ /** Minutes from now until the next occurrence of [hour]:[minute] (local). */+ private fun initialDelayMinutes(hour: Int, minute: Int): Long {+ val now = Calendar.getInstance()+ val next = Calendar.getInstance().apply {+ set(Calendar.HOUR_OF_DAY, hour)+ set(Calendar.MINUTE, minute)+ set(Calendar.SECOND, 0)+ set(Calendar.MILLISECOND, 0)+ if (before(now)) add(Calendar.DAY_OF_MONTH, 1)+ }+ return ((next.timeInMillis - now.timeInMillis) / 60_000L).coerceAtLeast(1)+ }+}++/**+ * Persisted reminder preferences for one game, so no game hand-rolls the key names.+ *+ * The time is stored as minutes since midnight rather than an hour/minute pair, which keeps it+ * to a single key and a single write.+ */+class DailyReminderSettings(context: Context, keyPrefix: String) {++ private val store = DataStoreUtils.getInstance(context)++ private val enabledKey = "${keyPrefix}_reminder_enabled"+ private val minutesKey = "${keyPrefix}_reminder_minutes"++ /** `DataStoreUtils.booleanFlow(name)` emits nothing until first written; this defaults it. */+ val enabled: Flow<Boolean> = store.booleanFlow(enabledKey, false)++ val minutesOfDay: Flow<Long> =+ store.longFlow(minutesKey, DailyPuzzleReminder.DEFAULT_MINUTES_OF_DAY)++ suspend fun setEnabled(enabled: Boolean) = store.setBoolean(enabledKey, enabled)++ suspend fun setMinutesOfDay(minutes: Long) = store.setLong(minutesKey, minutes)+}++/** Posts the nudge, unless today's puzzle is already done. */+class DailyPuzzleReminderWorker(+ appContext: Context,+ params: WorkerParameters,+) : CoroutineWorker(appContext, params) {++ override suspend fun doWork(): Result {+ val keyPrefix = DailyPuzzleReminder.keyPrefixOf(inputData) ?: return Result.success()+ val store = DailyChallengeStore(applicationContext, keyPrefix)+ // Games only record the day once every puzzle in it is solved, so "not today" is+ // exactly "not finished today" — no per-game logic needed here.+ if (store.lastCompletedDay() == store.todayEpochDay()) return Result.success()+ notify(DailyPuzzleReminder.notificationIdOf(inputData))+ return Result.success()+ }++ private fun notify(notificationId: Int) {+ val context = applicationContext+ // Re-checked at post time: the permission can be revoked after the work was scheduled.+ if (ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=+ PackageManager.PERMISSION_GRANTED+ ) {+ return+ }+ val appLabel = context.applicationInfo.loadLabel(context.packageManager).toString()+ context.ensureNotificationChannel(+ id = DailyPuzzleReminder.CHANNEL_ID,+ name = context.getString(R.string.daily_reminder_channel_name),+ importance = NotificationManager.IMPORTANCE_DEFAULT,+ description = context.getString(R.string.daily_reminder_channel_description),+ )+ val launch = context.packageManager.getLaunchIntentForPackage(context.packageName)+ ?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)+ val pending = launch?.let {+ PendingIntent.getActivity(+ context,+ 0,+ it,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ )+ }+ val notification = NotificationCompat.Builder(context, DailyPuzzleReminder.CHANNEL_ID)+ .setSmallIcon(android.R.drawable.ic_dialog_info)+ .setContentTitle(context.getString(R.string.daily_reminder_title))+ .setContentText(context.getString(R.string.daily_reminder_text, appLabel))+ .setAutoCancel(true)+ .apply { if (pending != null) setContentIntent(pending) }+ .build()+ NotificationManagerCompat.from(context).notify(notificationId, notification)+ }+}