diff --git a/CHANGELOG.md b/CHANGELOG.md index 64e05f8..0df7463 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,39 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Nothing yet. Open an issue or PR to propose something. +## [1.1.2] - 2026-11-08 + +Notifications now work on a device that has not opened the app for a while, and on a fresh install. + +### Fixed + +- **A fresh install could never show a notification.** Deal alerts are on by default, but on + Android 13 and above the notification permission starts denied, and the app only asked when the + switch was turned from off to on — which it never was. The app now explains why it needs the + permission and asks for it once, after the intro. "Not now" is remembered, and Settings keeps an + **Allow notifications** action. +- **Opening the app pushed the next background check back.** Every process start re-armed the + hourly alarm to a fresh hour, including the process starts WorkManager performs for its own + worker. On a device that was woken often enough, the punctual alarm never fired. An alarm that is + already armed is now left alone; only a firing, a reboot, an app update, or turning the feature + on or off changes it. +- **The check recorded changes it could not post.** If notifications were blocked when a sale was + detected, the app marked it as announced anyway, so granting the permission later brought + nothing back. The record is now left untouched until something is actually posted. +- **Free games were skipped when the wishlist was empty.** The worker returned early, even though + free games are announced without being saved. It now checks them regardless. +- **"Delete all app data" left the alert records behind.** It now clears the watch state and the + status record too, and restores the default schedule. + +### Added + +- **Deal-alert diagnostics in Settings.** The last-check line says when the last check ran and what + it did — checked, posted, blocked, no deals, or failed — and the next-check line says when the + next alarm is due. A **Check now** button runs one immediately. +- **A background-reliability hint.** If Android's battery optimisation is restricting the app, the + card says so and links to the battery settings, because several manufacturers defer background + work until the app is next opened. + ## [1.1.1] - 2026-10-22 The app can now find and install its own updates, and its Settings screen has an About section that @@ -223,7 +256,8 @@ failure mode behind every one. - **Price history is local.** The chart shows prices *this device* recorded. External databases are reachable through deep links rather than being scraped, because most of them block programmatic access. -[Unreleased]: https://github.com/JuggyBob/DiscountHunterAndroid/compare/v1.1.1...HEAD +[Unreleased]: https://github.com/JuggyBob/DiscountHunterAndroid/compare/v1.1.2...HEAD +[1.1.2]: https://github.com/JuggyBob/DiscountHunterAndroid/releases/tag/v1.1.2 [1.1.1]: https://github.com/JuggyBob/DiscountHunterAndroid/releases/tag/v1.1.1 [1.1.0]: https://github.com/JuggyBob/DiscountHunterAndroid/releases/tag/v1.1.0 [1.0.0]: https://github.com/JuggyBob/DiscountHunterAndroid/releases/tag/v1.0.0 \ No newline at end of file diff --git a/DEV_NOTES.md b/DEV_NOTES.md index f31d7aa..fce7075 100644 --- a/DEV_NOTES.md +++ b/DEV_NOTES.md @@ -788,6 +788,75 @@ The fix is two keep rules in `proguard-rules.pro`: -keep class * extends androidx.room.RoomDatabase { (); } -keep class androidx.work.impl.** { *; } ``` +### 4.44 The notification permission was never requested, because the feature was already on + +The most direct reason a fresh install could not show a notification, on any Android 13 or later +device. + +`saleAlertsEnabled` defaults to `true`. The only call to `requestPermissions(POST_NOTIFICATIONS)` +was in the Settings switch's `onCheckedChange`, guarded by `if (enabled)`. A new user therefore saw +the switch already on, never toggled it, and was never asked. The system denied the permission by +default, the background check ran, the watch state advanced, and every notification was dropped. +The feature looked enabled and did nothing. + +The fix is a one-time explanation after the intro, followed by the system request. The answer is +remembered in `AppSettings.hasPromptedNotificationPermission`, so "Not now" is respected; Settings +keeps an explicit "Allow notifications" action, because Android will not show the dialog again after +a permanent denial. + +### 4.45 Every app launch pushed the alarm an hour into the future + +The scheduler used two mechanisms on purpose: a punctual `AlarmManager` alarm and a deferrable +WorkManager periodic worker. The alarm is a chain - `DealAlertReceiver` re-arms the next one when it +fires - but `AppContainer.start()` also called `scheduleAlarm()` on **every process creation**. Each +call used `setExactAndAllowWhileIdle(now + 60 min)` with `FLAG_UPDATE_CURRENT`, which replaces the +pending alarm rather than leaving it alone. + +WorkManager starts the process for its own periodic worker. So the backstop was resetting the +punctual path every time it ran. A user who opened the app more often than hourly - or a device +whose periodic work ran often - could keep the alarm permanently an hour away. Only the deferrable +worker was left, and on a battery-managed phone that is exactly the "no notification when the app is +closed" report. + +The fix persists the due time, asks `PendingIntent.getBroadcast(..., FLAG_NO_CREATE)` whether the +alarm still exists, and leaves an armed alarm alone. `AlarmSchedule.shouldArm` is pure and tested: +force (a firing, a reboot, an app update), no pending alarm, or more than two intervals overdue. A +normally pending alarm is never moved. The alarm time in `dumpsys alarm` is byte-for-byte unchanged +across a process kill and relaunch. + +### 4.46 A notification that could not be posted was recorded as delivered + +The worker saved `detection.nextState` unconditionally. If `AlertNotifier.canPost()` was false - the +permission had not been granted, or the user had blocked the channel - `announce()` returned zero +and the state still recorded the sale as announced. Granting the permission later brought nothing +back, because the app believed it had already told the user. + +The worker now checks `canPost()` **before** fetching the feed and returns without touching the +record. `AlertDeliveryPolicy.shouldAdvanceState` also covers the permission being revoked between +the check and the post: the record advances only when there was nothing to announce, something was +actually posted, or this was the first run establishing its baseline. The first-run case is +deliberate - without it every run would look like a first run and announce nothing. + +### 4.47 An empty wishlist disabled free-game alerts + +`SaleDetector` announces free games whether or not they are saved. The worker, however, returned +early when the wishlist was empty, with the log line "nothing to watch for". A user with no saved +games therefore never received a free-game notification, which is the one alert the feature promises +without any setup. + +The early return is gone. The detector already handles an empty wishlist; the feed is still fetched +and the free-game half still runs. The status record shows `wishlist: 0` rather than hiding the +check. + +### 4.48 "Delete all app data" left the alert records behind + +`deleteAllData()` cleared the payload cache, the snapshots and the settings, but not +`files/alerts/watch-state.json` or the new status file. The next check could therefore believe it +had already announced sales from before the wipe, and the Settings status described a check that +belonged to deleted data. It now deletes both, resets the in-memory status, and restarts the default +schedule - because the settings return to `saleAlertsEnabled = true`, and a schedule that had been +stopped would otherwise stay stopped while the switch showed on. + --- ## 5. Design decisions worth explaining diff --git a/README.md b/README.md index 2ce3eb1..1e9fd31 100644 --- a/README.md +++ b/README.md @@ -36,16 +36,17 @@ games to watch their prices. Settings, including log export

-## What is new in 1.1.1 +## What is new in 1.1.2 -**The app can now update itself.** Settings has a *Check for updates* entry that finds a newer -release, downloads it, and starts Android's own installer for it — and an *About* dialog that shows -the version you are on, the version published most recently, and the release notes for it, fetched -from the official GitHub release. +**Deal alerts now work when the app has been closed, and on a fresh install.** There were four +separate reasons they could fail silently: a device on Android 13+ was never asked for the +notification permission, opening the app kept pushing the hourly check back, a sale detected while +notifications were blocked was recorded as delivered, and free games were skipped when nothing was +saved. -Nothing is fetched until you ask, nothing is downloaded until you ask for that, and the -installation itself is still confirmed by Android, in the normal way. See -[CHANGELOG.md](CHANGELOG.md) for the full list. +Settings now also shows when the last check ran, what it did, and when the next one is due, with a +**Check now** button — and points out Android's battery optimisation when it is restricting +background work. See [CHANGELOG.md](CHANGELOG.md) for the details. ## Download diff --git a/app/build.gradle.kts b/app/build.gradle.kts index f4b1ca6..f85416f 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -37,8 +37,8 @@ android { targetSdk = 36 // Must be higher than any build already installed on a user's device, or the install is // refused as a downgrade. The device this was built against had 1.0.1-release at code 7. - versionCode = 9 - versionName = "1.1.1-release" + versionCode = 10 + versionName = "1.1.2-release" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } diff --git a/app/src/main/java/com/discounthunter/android/MainActivity.kt b/app/src/main/java/com/discounthunter/android/MainActivity.kt index 7259336..9230856 100644 --- a/app/src/main/java/com/discounthunter/android/MainActivity.kt +++ b/app/src/main/java/com/discounthunter/android/MainActivity.kt @@ -77,6 +77,7 @@ import com.discounthunter.android.ui.search.SearchScreen import com.discounthunter.android.ui.search.SearchViewModel import com.discounthunter.android.ui.settings.SettingsScreen import com.discounthunter.android.ui.settings.SettingsViewModel +import com.discounthunter.android.ui.settings.NotificationPermissionPrompt import com.discounthunter.android.ui.theme.DiscountHunterTheme import com.discounthunter.android.ui.theme.Motion import com.discounthunter.android.ui.wishlist.WishlistScreen @@ -481,6 +482,10 @@ private fun MainShell( } } } + + // Asked once, after the tour, when the main app is actually on screen. On Android 13 and above + // the deal-alerts feature cannot post anything without it, and the feature is on by default. + NotificationPermissionPrompt(container) } /** Reconstructs the reference from the route arguments. */ diff --git a/app/src/main/java/com/discounthunter/android/alerts/AlertDeliveryPolicy.kt b/app/src/main/java/com/discounthunter/android/alerts/AlertDeliveryPolicy.kt new file mode 100644 index 0000000..8e5ae85 --- /dev/null +++ b/app/src/main/java/com/discounthunter/android/alerts/AlertDeliveryPolicy.kt @@ -0,0 +1,34 @@ +package com.discounthunter.android.alerts + +/** + * Whether a check may record what it detected as "announced". + * + * ## The rule + * + * The watch state is what stops the same sale being announced twice. Advancing it is therefore a + * promise that the user *saw* the announcement. If the check detected something but could post + * nothing — the notification permission was revoked between the check and the post, or the system + * refused every notification — advancing the state would silently consume the news: granting the + * permission later would not bring it back. + * + * There are two legitimate reasons to advance anyway: + * + * * there was nothing to announce, so there is nothing to consume; and + * * this was the first run, whose purpose is to establish a baseline. It has no announcements by + * definition, and without the baseline every later run would look like a first run. + * + * Pure so the rule can be tested without a worker, a notifier or an Android permission. + */ +object AlertDeliveryPolicy { + + /** + * @param hasAnythingToAnnounce whether the detector produced sales or free games. + * @param posted how many notifications the notifier actually posted. + * @param previouslyInitialised whether a baseline existed before this check. + */ + fun shouldAdvanceState( + hasAnythingToAnnounce: Boolean, + posted: Int, + previouslyInitialised: Boolean, + ): Boolean = !hasAnythingToAnnounce || posted > 0 || !previouslyInitialised +} diff --git a/app/src/main/java/com/discounthunter/android/alerts/AlertStatusStore.kt b/app/src/main/java/com/discounthunter/android/alerts/AlertStatusStore.kt new file mode 100644 index 0000000..a6c7974 --- /dev/null +++ b/app/src/main/java/com/discounthunter/android/alerts/AlertStatusStore.kt @@ -0,0 +1,171 @@ +package com.discounthunter.android.alerts + +import com.discounthunter.android.core.text.Json +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.withContext +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import java.io.File + +/** + * What the last background check did. + * + * ## Why this exists + * + * A background feature that only ever reports "no notification" is impossible to diagnose, from + * either side. The user cannot tell whether the check ran and found nothing, ran and was blocked by + * a permission, or never ran at all — and the app cannot say, because a worker that logs to a + * ring buffer the user never opens has effectively said nothing. + * + * This is a tiny record of the last run, shown in Settings. It is deliberately *not* a history: one + * entry is enough to answer "is this alive, and what did it do last time". + */ +enum class AlertCheckOutcome { + /** The check ran and found nothing to announce. */ + CHECKED, + + /** The check ran and posted at least one notification. */ + ANNOUNCED, + + /** The check was skipped because notifications are blocked or not permitted. */ + NOTIFICATIONS_BLOCKED, + + /** The check was skipped because the stores returned no deals. */ + FEED_EMPTY, + + /** The check was skipped because the user has deal alerts switched off. */ + MONITORING_OFF, + + /** The check threw, and will be retried by WorkManager. */ + FAILED, +} + +/** One completed (or skipped) background check. */ +data class AlertRunStatus( + /** When the check happened, in epoch millis. */ + val checkedAt: Long, + val outcome: AlertCheckOutcome, + /** How many notifications were posted. */ + val announced: Int = 0, + /** How many deals the feed contained. */ + val deals: Int = 0, + /** How many games were saved when the check ran. */ + val wishlist: Int = 0, + /** A short diagnostic message. Never contains credentials or store payloads. */ + val message: String = "", +) + +/** + * Reads and writes [AlertRunStatus]. + * + * `filesDir`, not `cacheDir`: the system may clear the cache at any moment, and "when did this last + * run" is precisely the question a user asks after the cache has been cleared. + * + * A corrupt or missing file reads as null, which the Settings screen shows as "no check has run + * yet". That is the safe direction — it never claims a check succeeded when the record is gone. + */ +class AlertStatusStore( + private val file: File, + private val io: CoroutineDispatcher = Dispatchers.IO, +) { + + /** Reads the last recorded check, or null when there is no usable record. */ + suspend fun load(): AlertRunStatus? = withContext(io) { + if (!file.isFile) return@withContext null + val status = runCatching { file.readText() }.getOrNull()?.let(AlertStatusCodec::parse) + // Seeding the process-wide flow here is what lets a ViewModel that starts after a worker + // see the result: the flow's initial value is null, and this is the first real value. + status?.let { publish(it) } + status + } + + /** + * Records the outcome of a check. + * + * The write is atomic through a sibling file, so a process death mid-write cannot leave a + * half-written record. A failure is logged by the caller rather than thrown: this is + * diagnostics, and diagnostics must never be the reason a notification is not posted. + */ + suspend fun record(status: AlertRunStatus) = withContext(io) { + runCatching { + file.parentFile?.mkdirs() + val temp = File(file.parentFile, "${file.name}.tmp") + temp.writeText(AlertStatusCodec.serialize(status)) + if (!temp.renameTo(file)) { + file.writeText(AlertStatusCodec.serialize(status)) + temp.delete() + } + }.onSuccess { + // Published immediately so an open Settings screen updates without being reopened. + // The process may have been started just for this worker, in which case nobody is + // listening — the file is the durable copy. + publish(status) + } + } + + companion object { + + private val _latest = MutableStateFlow(null) + + /** + * The latest record in this process, or null before anything has been read or written. + * + * A process-wide flow because the writer is a worker and the reader is a ViewModel; a file + * alone would leave the screen showing the previous run until it was reopened. + */ + val latest: StateFlow = _latest.asStateFlow() + + internal fun publish(status: AlertRunStatus) { + _latest.value = status + } + + /** Forgets the in-memory record, for "delete all app data". */ + fun reset() { + _latest.value = null + } + } +} + +/** + * The on-disk shape of [AlertRunStatus]. + * + * Hand-written rather than reflective, like the rest of the project's storage: the file is small, + * the schema is explicit, and an unreadable field can be defaulted without a crash. + */ +object AlertStatusCodec { + + fun serialize(status: AlertRunStatus): String = JsonObject( + mapOf( + "checkedAt" to JsonPrimitive(status.checkedAt), + "outcome" to JsonPrimitive(status.outcome.name), + "announced" to JsonPrimitive(status.announced), + "deals" to JsonPrimitive(status.deals), + "wishlist" to JsonPrimitive(status.wishlist), + "message" to JsonPrimitive(status.message.take(MAX_MESSAGE_LENGTH)), + ), + ).toString() + + /** Parses a record, returning null when it is not one. */ + fun parse(text: String): AlertRunStatus? { + val root = Json.parse(text) as? JsonObject ?: return null + val checkedAt = Json.str(root, "checkedAt").toLongOrNull() ?: return null + val outcome = runCatching { + AlertCheckOutcome.valueOf(Json.str(root, "outcome")) + }.getOrNull() ?: return null + return AlertRunStatus( + checkedAt = checkedAt, + outcome = outcome, + announced = Json.int(root, "announced").coerceAtLeast(0), + deals = Json.int(root, "deals").coerceAtLeast(0), + wishlist = Json.int(root, "wishlist").coerceAtLeast(0), + message = Json.str(root, "message").take(MAX_MESSAGE_LENGTH), + ) + } + + /** A diagnostic message is truncated so the file cannot grow with an exception's stack text. */ + private const val MAX_MESSAGE_LENGTH = 300 +} diff --git a/app/src/main/java/com/discounthunter/android/alerts/BootReceiver.kt b/app/src/main/java/com/discounthunter/android/alerts/BootReceiver.kt index a608c1a..54f4af5 100644 --- a/app/src/main/java/com/discounthunter/android/alerts/BootReceiver.kt +++ b/app/src/main/java/com/discounthunter/android/alerts/BootReceiver.kt @@ -3,19 +3,26 @@ package com.discounthunter.android.alerts import android.content.BroadcastReceiver import android.content.Context import android.content.Intent +import com.discounthunter.android.DiscountHunterApplication import com.discounthunter.android.diagnostics.AppLog +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull /** - * Restores the schedule after a reboot. + * Restores the schedule after a reboot or an app update. * - * Alarms do not survive a restart, and WorkManager's own schedule *does* — so this is not about - * the periodic worker, which would come back on its own. It is about the alarm heartbeat, which - * is the punctual half of the arrangement and would otherwise be silently gone after every - * reboot. + * Alarms do not survive either event, and WorkManager's own schedule *does* survive both — so this + * is not about the periodic worker, which would come back on its own. It is about the alarm + * heartbeat, which is the punctual half of the arrangement and would otherwise be silently gone + * after every reboot. * - * The worker is re-registered as well, because the user's setting is the source of truth for - * whether monitoring should be running at all: if they turned it off, a reboot must not turn it - * back on. + * The user's setting decides whether anything is restored. A reboot must never switch monitoring + * back on for someone who deliberately turned it off, and it must not keep waking the device every + * hour for a feature that is not running. */ class BootReceiver : BroadcastReceiver() { @@ -26,13 +33,51 @@ class BootReceiver : BroadcastReceiver() { } AppLog.i("Alerts: the device started, restoring the check schedule") - val pending = goAsync() - val appContext = context.applicationContext + val app = context.applicationContext as? DiscountHunterApplication + val container = app?.container + if (app == null || container == null) { + // The container is created in Application.onCreate, which runs before a manifest + // receiver. This is therefore an unexpected state, not a normal one; the periodic + // worker is persisted and will still run. + AppLog.w("Alerts: the container is not ready, so the schedule was not restored") + return + } + // The work is queued rather than done inline: on a boot broadcast the device may still be // finishing its own start-up, and a network call then would be competing with everything - // else the system is doing. - DealAlertScheduler.enqueueNow(appContext) - DealAlertScheduler.scheduleAlarm(appContext) - pending.finish() + // else the system is doing. `goAsync` gives the DataStore read the same window the + // broadcast itself has. + val pending = goAsync() + CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { + try { + val enabled = runCatching { + // The broadcast has about ten seconds. A DataStore read is normally + // instantaneous, but this is a boot-time broadcast competing with the rest of + // the system's start-up, so it gets a bound rather than the whole window. + withTimeoutOrNull(8_000) { container.settings.settings.first() } + }.getOrNull()?.saleAlertsEnabled + when (enabled) { + true -> { + AlertNotifier(app, container.fxRates).ensureChannels() + // Forced: the system cleared every alarm when it rebooted or replaced the + // package, so there is nothing here to push back. + DealAlertScheduler.start(app, forceAlarm = true) + // Check soon rather than waiting a full interval: the device may have been + // off for days, and a sale could have started and be about to end. + DealAlertScheduler.enqueueNow(app) + AppLog.i("Alerts: schedule restored after a restart") + } + + false -> { + DealAlertScheduler.stop(app) + AppLog.i("Alerts: monitoring is off, so nothing was restored") + } + + null -> AppLog.w("Alerts: the setting could not be read, leaving the schedule alone") + } + } finally { + pending.finish() + } + } } } diff --git a/app/src/main/java/com/discounthunter/android/alerts/DealAlertReceiver.kt b/app/src/main/java/com/discounthunter/android/alerts/DealAlertReceiver.kt index 9ccea64..e8a2fd8 100644 --- a/app/src/main/java/com/discounthunter/android/alerts/DealAlertReceiver.kt +++ b/app/src/main/java/com/discounthunter/android/alerts/DealAlertReceiver.kt @@ -22,8 +22,9 @@ class DealAlertReceiver : BroadcastReceiver() { if (intent.action != DealAlertScheduler.ACTION_CHECK) return AppLog.i("Alerts: the alarm fired") // Re-arm first. If the process is killed between here and the work being queued, the next - // alarm is already in place. - DealAlertScheduler.scheduleAlarm(context) + // alarm is already in place. `force` because this firing is what consumes the old alarm: + // the chain must continue with a fresh 60 minutes. + DealAlertScheduler.scheduleAlarm(context, force = true) DealAlertScheduler.enqueueNow(context) } } diff --git a/app/src/main/java/com/discounthunter/android/alerts/DealAlertScheduler.kt b/app/src/main/java/com/discounthunter/android/alerts/DealAlertScheduler.kt index 7b65cc2..4b2d56d 100644 --- a/app/src/main/java/com/discounthunter/android/alerts/DealAlertScheduler.kt +++ b/app/src/main/java/com/discounthunter/android/alerts/DealAlertScheduler.kt @@ -58,9 +58,13 @@ object DealAlertScheduler { * Starts monitoring. * * Safe to call repeatedly: the periodic worker uses [ExistingPeriodicWorkPolicy.KEEP], so an - * existing schedule is left alone rather than restarted on every app launch. + * existing schedule is left alone rather than restarted on every app launch, and + * [scheduleAlarm] leaves an alarm that is already armed where it is. + * + * [forceAlarm] is for the two moments when the alarm is genuinely gone: a reboot, and an app + * replacement. Both clear every pending alarm, so restoring one is not "resetting" it. */ - fun start(context: Context) { + fun start(context: Context, forceAlarm: Boolean = false) { val workManager = WorkManager.getInstance(context) val constraints = Constraints.Builder() @@ -84,14 +88,17 @@ object DealAlertScheduler { periodic, ) - scheduleAlarm(context) + scheduleAlarm(context, force = forceAlarm) AppLog.i("Alerts: monitoring scheduled (every $CHECK_INTERVAL_MINUTES min)") } /** Stops monitoring and cancels anything already queued. */ fun stop(context: Context) { runCatching { WorkManager.getInstance(context).cancelUniqueWork(PERIODIC_WORK) } - runCatching { WorkManager.getInstance(context).cancelUniqueWork(ONE_TIME_WORK) } + // The one-time checks are enqueued under a tag rather than a unique name (see + // [enqueueNow]), so cancelling them has to be by tag. `cancelUniqueWork` would silently + // cancel nothing here. + runCatching { WorkManager.getInstance(context).cancelAllWorkByTag(ONE_TIME_WORK) } cancelAlarm(context) AppLog.i("Alerts: monitoring stopped") } @@ -99,35 +106,74 @@ object DealAlertScheduler { /** * Schedules the next alarm. * - * Called from [DealAlertReceiver] after each run, so the alarm keeps itself alive. The - * receiver re-arms rather than using a repeating alarm, because a repeating alarm is lost the - * moment the app is updated and has to be re-armed anyway. + * ## Why an existing alarm is left alone + * + * The alarm is a chain: each firing re-arms the next one. It must therefore never be pushed + * back by anything other than a firing. This used to be called unconditionally from + * [AppContainer.start], which runs on **every process creation** — including the ones + * WorkManager creates for its periodic worker. Each of those starts moved the alarm another + * hour into the future, so on a device that was woken often enough the punctual half of the + * schedule never fired at all. Only the deferrable periodic worker was left, which is exactly + * the "no notification when the app is closed" complaint on battery-managed phones. + * + * [force] is used by the receiver after a firing (the chain must continue) and by the boot and + * package-replaced receivers (the system clears alarms at both moments). */ - fun scheduleAlarm(context: Context) { + fun scheduleAlarm(context: Context, force: Boolean = false) { val manager = context.getSystemService(AlarmManager::class.java) ?: return - val triggerAt = System.currentTimeMillis() + CHECK_INTERVAL_MINUTES * 60_000L + val now = System.currentTimeMillis() + val nextAt = storedNextAlarmAt(context) + val pending = pendingAlarm(context) + + if (!AlarmSchedule.shouldArm(now, nextAt, pending != null, force)) { + AppLog.i("Alerts: the next check is already armed; leaving it alone") + return + } + + val triggerAt = now + CHECK_INTERVAL_MINUTES * 60_000L + val armed = arm(manager, triggerAt, pending ?: createAlarmIntent(context)) + if (armed) { + // Remembered so the next process start can tell "armed and waiting" from "lost". + schedulePrefs(context).edit().putLong(KEY_NEXT_ALARM_AT, triggerAt).apply() + } + } + + /** Cancels the pending alarm. */ + fun cancelAlarm(context: Context) { + val manager = context.getSystemService(AlarmManager::class.java) ?: return + pendingAlarm(context)?.let { runCatching { manager.cancel(it) } } + schedulePrefs(context).edit().remove(KEY_NEXT_ALARM_AT).apply() + } - val pending = alarmIntent(context) - try { + /** + * When the next alarm should fire, or null when none is armed. + * + * Used by the Settings screen to say when the next check is due, so a user who is wondering + * whether the feature is alive has something concrete to look at. + */ + fun nextAlarmAt(context: Context): Long? = storedNextAlarmAt(context).takeIf { it > 0L } + + /** Arms the alarm, exact when permitted and inexact when not. Returns true when it took. */ + private fun arm(manager: AlarmManager, triggerAt: Long, pending: PendingIntent): Boolean { + return try { if (canScheduleExact(manager)) { manager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pending) } else { // Inexact, but still delivered inside a Doze window, and it needs no permission. manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pending) } + true } catch (error: SecurityException) { // The exact-alarm permission was revoked between the check and the call. AppLog.w("Alerts: exact alarms are not permitted, falling back to an inexact alarm") runCatching { manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAt, pending) } + .isSuccess + } catch (error: Exception) { + AppLog.e("Alerts: the next check could not be armed", error) + false } } - /** Cancels the pending alarm. */ - fun cancelAlarm(context: Context) { - val manager = context.getSystemService(AlarmManager::class.java) ?: return - runCatching { manager.cancel(alarmIntent(context)) } - } - /** * Queues the check to run now. * @@ -166,7 +212,7 @@ object DealAlertScheduler { .onFailure { AppLog.e("Alerts: could not queue a check", it) } } - private fun alarmIntent(context: Context): PendingIntent { + private fun createAlarmIntent(context: Context): PendingIntent { val intent = Intent(context, DealAlertReceiver::class.java).setAction(ACTION_CHECK) return PendingIntent.getBroadcast( context, @@ -176,6 +222,28 @@ object DealAlertScheduler { ) } + /** + * The alarm this app already has pending, or null when there is none. + * + * `FLAG_NO_CREATE` asks for the existing token rather than creating one, which is what makes + * it possible to tell "armed" from "lost" without keeping a second copy of the truth. + */ + private fun pendingAlarm(context: Context): PendingIntent? { + val intent = Intent(context, DealAlertReceiver::class.java).setAction(ACTION_CHECK) + return PendingIntent.getBroadcast( + context, + REQUEST_CODE, + intent, + PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE, + ) + } + + private fun schedulePrefs(context: Context) = + context.getSharedPreferences(SCHEDULE_PREFS, Context.MODE_PRIVATE) + + private fun storedNextAlarmAt(context: Context): Long = + schedulePrefs(context).getLong(KEY_NEXT_ALARM_AT, 0L) + private fun canScheduleExact(manager: AlarmManager): Boolean = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { runCatching { manager.canScheduleExactAlarms() }.getOrDefault(false) @@ -186,4 +254,50 @@ object DealAlertScheduler { /** The action the alarm carries. */ const val ACTION_CHECK = "com.discounthunter.android.action.CHECK_DEALS" private const val REQUEST_CODE = 7311 + private const val SCHEDULE_PREFS = "deal_alert_schedule" + private const val KEY_NEXT_ALARM_AT = "next_alarm_at" +} + +/** + * The decision of whether the next alarm needs to be armed. + * + * Pure and separate from [DealAlertScheduler] so it can be tested without an `AlarmManager`. The + * rule is deliberately conservative: an alarm that is armed is left alone unless it is provably + * gone, or so far overdue that the chain must have broken. + */ +object AlarmSchedule { + + /** + * How many intervals past its due time an alarm may be before it is treated as lost. + * + * A pending alarm can legitimately be late: Doze defers even `setExactAndAllowWhileIdle`, and a + * device that was asleep for an hour may deliver it well after the time it was set for. + * Resetting it then would delay it by another full interval, which is the opposite of what is + * wanted. Two intervals is late enough to be suspicious, early enough to recover. + */ + const val STALE_AFTER_INTERVALS = 2 + + /** + * True when [scheduleAlarm][DealAlertScheduler.scheduleAlarm] should call the AlarmManager. + * + * @param now the current wall-clock time in epoch millis. + * @param nextAlarmAt when the stored alarm is due, or 0 when that is not known. + * @param hasPendingAlarm whether the platform still has the `PendingIntent`. + * @param force true when the caller knows the alarm was cleared (a reboot or an app update). + * @param intervalMillis the normal gap between checks. + */ + fun shouldArm( + now: Long, + nextAlarmAt: Long, + hasPendingAlarm: Boolean, + force: Boolean, + intervalMillis: Long = DealAlertScheduler.CHECK_INTERVAL_MINUTES * 60_000L, + ): Boolean { + if (force) return true + if (!hasPendingAlarm) return true + // Armed, but the stored time is missing: leave the platform's copy alone. The receiver + // re-arms when it fires, and WorkManager is the backstop if it never does. + if (nextAlarmAt <= 0L) return false + return now - nextAlarmAt > intervalMillis * STALE_AFTER_INTERVALS + } } diff --git a/app/src/main/java/com/discounthunter/android/alerts/DealAlertWorker.kt b/app/src/main/java/com/discounthunter/android/alerts/DealAlertWorker.kt index 417d661..825edf3 100644 --- a/app/src/main/java/com/discounthunter/android/alerts/DealAlertWorker.kt +++ b/app/src/main/java/com/discounthunter/android/alerts/DealAlertWorker.kt @@ -49,21 +49,46 @@ class DealAlertWorker( return Result.retry() } + val statusStore = AlertStatusStore(container.alertStatusFile) try { val settings = container.settings.settings.first() if (!settings.saleAlertsEnabled) { AppLog.i("Alerts: monitoring is off, skipping this check") + statusStore.record( + AlertRunStatus( + checkedAt = System.currentTimeMillis(), + outcome = AlertCheckOutcome.MONITORING_OFF, + ), + ) + return Result.success() + } + + // Check the permission *before* fetching the feed. There is no point spending a + // network round trip on a notification that cannot be posted, and — more importantly — + // the watch state must not be advanced for something the user was never told about. + // Leaving it alone means the change is still there to announce once the permission is + // granted, rather than having been silently consumed. + val notifier = AlertNotifier(applicationContext, container.fxRates) + if (!notifier.canPost()) { + AppLog.w("Alerts: notifications are not allowed, so the check was skipped") + statusStore.record( + AlertRunStatus( + checkedAt = System.currentTimeMillis(), + outcome = AlertCheckOutcome.NOTIFICATIONS_BLOCKED, + ), + ) return Result.success() } // The wishlist lives in memory and is mirrored from DataStore. A worker may be the very // first thing to run in a fresh process, so it has to be loaded rather than assumed. + // + // An empty wishlist does **not** end the check: free games are announced whether or + // not anything is saved (see [SaleDetector]), so the feed is still fetched and the + // free-game half of the detector still runs. Returning here would silently disable + // free-game alerts for every user who has not saved anything yet. container.wishlist.loadOnce() val wishlist = container.wishlist.entries.value - if (wishlist.isEmpty()) { - AppLog.i("Alerts: the wishlist is empty, nothing to watch for") - return Result.success() - } val feed = container.deals.refreshFeed( country = settings.steamCountry, @@ -76,6 +101,13 @@ class DealAlertWorker( AppLog.w("Alerts: the feed came back empty, so nothing could be checked") // Not a failure: the stores may simply be down. Retrying immediately would hammer // them, so this is a success with no work done. + statusStore.record( + AlertRunStatus( + checkedAt = System.currentTimeMillis(), + outcome = AlertCheckOutcome.FEED_EMPTY, + wishlist = wishlist.size, + ), + ) return Result.success() } @@ -88,26 +120,53 @@ class DealAlertWorker( matches = { entry, deal -> representsSame(entry, deal.wishlistKey, deal.titleKey) }, ) - val notifier = AlertNotifier(applicationContext, container.fxRates) val posted = notifier.announce( detection = detection, currencySymbol = settings.currencySymbol, currencyCode = settings.currency.code, ) - // The state is written whether or not anything was announced. Skipping the write when - // there is nothing to say would lose the record of what has been seen, and the next - // check would announce everything again. - store.save(detection.nextState) + // The state is written when there is nothing to announce, and when what was announced + // actually reached the user. If there was something to say and nothing could be + // posted — the permission can be revoked between the check above and this line — the + // old record is kept, so the next check tries again instead of treating a notification + // the user never saw as delivered. + val advance = AlertDeliveryPolicy.shouldAdvanceState( + hasAnythingToAnnounce = detection.hasAnythingToAnnounce, + posted = posted, + previouslyInitialised = previous.initialised, + ) + if (advance) { + store.save(detection.nextState) + } else { + AppLog.w("Alerts: nothing could be posted, so the record was left for the next check") + } + AppLog.i( "Alerts: checked ${feed.deals.size} deals, announced $posted, " + "watching ${wishlist.size} saved game(s)", ) + statusStore.record( + AlertRunStatus( + checkedAt = System.currentTimeMillis(), + outcome = if (posted > 0) AlertCheckOutcome.ANNOUNCED else AlertCheckOutcome.CHECKED, + announced = posted, + deals = feed.deals.size, + wishlist = wishlist.size, + ), + ) return Result.success() } catch (cancellation: kotlinx.coroutines.CancellationException) { throw cancellation } catch (error: Exception) { AppLog.e("Alerts: the check failed", error) + statusStore.record( + AlertRunStatus( + checkedAt = System.currentTimeMillis(), + outcome = AlertCheckOutcome.FAILED, + message = error.message.orEmpty(), + ), + ) // Retry, but not in a tight loop: WorkManager backs off on its own. return Result.retry() } diff --git a/app/src/main/java/com/discounthunter/android/alerts/NotificationPermissionPolicy.kt b/app/src/main/java/com/discounthunter/android/alerts/NotificationPermissionPolicy.kt new file mode 100644 index 0000000..d1b9a89 --- /dev/null +++ b/app/src/main/java/com/discounthunter/android/alerts/NotificationPermissionPolicy.kt @@ -0,0 +1,60 @@ +package com.discounthunter.android.alerts + +import android.os.Build + +/** + * Whether the app should ask for the notification permission. + * + * ## Why this is a separate, pure decision + * + * The permission only exists from Android 13 (API 33), and it is denied on a fresh install. The + * deal-alerts feature is enabled by default, so without a request the app schedules background + * checks that can never show anything: the setting looks on, the work runs, and nothing arrives. + * That was the state a fresh install was in. + * + * Asking must also be *once*: a user who has declined should not be asked again every time they + * open the app. The answer is remembered in settings, and the Settings screen keeps a manual way + * to grant the permission later. + * + * The logic is here rather than in the composable so it can be tested on the JVM without an + * Activity, which is where permission bugs usually hide. + */ +object NotificationPermissionPolicy { + + /** The first API level with a runtime notification permission. */ + const val RUNTIME_PERMISSION_API = Build.VERSION_CODES.TIRAMISU + + /** + * True when the one-time explanation should be shown. + * + * @param apiLevel the device's API level (`Build.VERSION.SDK_INT`). + * @param alertsEnabled whether the user has deal alerts switched on. + * @param canPost whether notifications are currently allowed. + * @param alreadyPrompted whether the explanation has been shown before. + */ + fun shouldPrompt( + apiLevel: Int, + alertsEnabled: Boolean, + canPost: Boolean, + alreadyPrompted: Boolean, + ): Boolean = + apiLevel >= RUNTIME_PERMISSION_API && + alertsEnabled && + !canPost && + !alreadyPrompted + + /** + * True when the app can still show the system permission dialog itself. + * + * Below Android 13 there is no runtime permission to request: if notifications are off, the + * only place to change that is the system settings screen. On 13 and above the dialog can be + * shown again; if the user has permanently denied it, Android answers immediately without a + * dialog, and the Settings screen's "Open settings" action is the way back. + */ + fun canRequestFromApp(apiLevel: Int, canPost: Boolean): Boolean = + apiLevel >= RUNTIME_PERMISSION_API && !canPost + + /** True when the Settings screen should warn that the feature cannot post anything. */ + fun shouldWarn(alertsEnabled: Boolean, canPost: Boolean): Boolean = + alertsEnabled && !canPost +} diff --git a/app/src/main/java/com/discounthunter/android/data/settings/AppSettings.kt b/app/src/main/java/com/discounthunter/android/data/settings/AppSettings.kt index c2b13d8..7c51d4f 100644 --- a/app/src/main/java/com/discounthunter/android/data/settings/AppSettings.kt +++ b/app/src/main/java/com/discounthunter/android/data/settings/AppSettings.kt @@ -36,6 +36,14 @@ data class AppSettings( * nobody ever turns on. */ val saleAlertsEnabled: Boolean = true, + /** + * Whether the one-time notification-permission explanation has been shown. + * + * On Android 13 and above the permission has to be granted at runtime, and a fresh install has + * it denied. The deal-alerts feature is on by default, so the app has to ask — but only + * once, and never again after a "not now". The Settings screen keeps a manual way back in. + */ + val hasPromptedNotificationPermission: Boolean = false, val recentSearches: List = emptyList(), val linkedAccounts: Map = emptyMap(), val wishlist: List = emptyList(), diff --git a/app/src/main/java/com/discounthunter/android/data/settings/SettingsRepository.kt b/app/src/main/java/com/discounthunter/android/data/settings/SettingsRepository.kt index 307bcb3..e3a4386 100644 --- a/app/src/main/java/com/discounthunter/android/data/settings/SettingsRepository.kt +++ b/app/src/main/java/com/discounthunter/android/data/settings/SettingsRepository.kt @@ -67,6 +67,15 @@ class SettingsRepository(context: Context) { /** Turns the background sale and free-game announcements on or off. */ suspend fun setSaleAlertsEnabled(enabled: Boolean) = edit { it[KEY_SALE_ALERTS] = enabled } + /** + * Remembers that the notification-permission explanation has been shown. + * + * Stored even when the user declines, so the app asks once and then respects the answer. The + * Settings screen always offers a way back, so this is not a dead end. + */ + suspend fun setNotificationPermissionPromptShown(shown: Boolean = true) = + edit { it[KEY_NOTIFICATION_PROMPT] = shown } + suspend fun rememberSearch(query: String) = edit { preferences -> val trimmed = query.trim() if (trimmed.isEmpty()) return@edit @@ -109,6 +118,7 @@ class SettingsRepository(context: Context) { autoplayTrailers = this[KEY_AUTOPLAY] ?: false, preferStoreApps = this[KEY_STORE_APPS] ?: true, saleAlertsEnabled = this[KEY_SALE_ALERTS] ?: true, + hasPromptedNotificationPermission = this[KEY_NOTIFICATION_PROMPT] ?: false, recentSearches = decodeSearches(this[KEY_SEARCHES]), linkedAccounts = decodeAccounts(this[KEY_ACCOUNTS]), wishlist = decodeWishlist(this[KEY_WISHLIST]), @@ -224,7 +234,8 @@ class SettingsRepository(context: Context) { val KEY_DEAL_LIMIT = intPreferencesKey("deal_limit") val KEY_AUTOPLAY = booleanPreferencesKey("autoplay_trailers") val KEY_STORE_APPS = booleanPreferencesKey("prefer_store_apps") - val KEY_SALE_ALERTS = booleanPreferencesKey("sale_alerts_enabled") + val KEY_SALE_ALERTS = booleanPreferencesKey("sale_alerts_enabled") + val KEY_NOTIFICATION_PROMPT = booleanPreferencesKey("notification_permission_prompted") val KEY_SEARCHES = stringPreferencesKey("recent_searches") val KEY_ACCOUNTS = stringPreferencesKey("linked_accounts") val KEY_WISHLIST = stringPreferencesKey("wishlist") diff --git a/app/src/main/java/com/discounthunter/android/di/AppContainer.kt b/app/src/main/java/com/discounthunter/android/di/AppContainer.kt index 1443bf9..5cab18b 100644 --- a/app/src/main/java/com/discounthunter/android/di/AppContainer.kt +++ b/app/src/main/java/com/discounthunter/android/di/AppContainer.kt @@ -2,6 +2,7 @@ package com.discounthunter.android.di import android.content.Context import com.discounthunter.android.alerts.AlertNotifier +import com.discounthunter.android.alerts.AlertStatusStore import com.discounthunter.android.alerts.DealAlertScheduler import com.discounthunter.android.alerts.WatchStateStore import com.discounthunter.android.core.model.FxRates @@ -136,6 +137,15 @@ class AppContainer( */ val watchStateFile: File = File(appContext.filesDir, "alerts/watch-state.json") + /** + * Where the result of the last background check is recorded, for the Settings screen. + * + * Separate from the watch state: that file decides what is announced, this one explains what + * happened. Mixing them would mean a diagnostic write could never be allowed to fail without + * affecting the announcement decision. + */ + val alertStatusFile: File = File(appContext.filesDir, "alerts/status.json") + /** The store behind the background announcements. */ val watchStateStore = WatchStateStore(watchStateFile) @@ -169,7 +179,19 @@ class AppContainer( suspend fun deleteAllData() { payloadCache.clear() snapshotStore.clear() + // The alert records are application data too. Leaving the watch state behind would make + // the first check after a wipe think it had already announced sales from before it; the + // status record would describe a check that belongs to the deleted data. + runCatching { watchStateFile.delete() } + runCatching { alertStatusFile.delete() } + AlertStatusStore.reset() settings.reset() + + // Settings now hold their defaults, and the default for deal alerts is on. If the user had + // turned them off, the schedule was stopped and would otherwise stay stopped while the + // switch showed on. + AlertNotifier(appContext, fxRates).ensureChannels() + DealAlertScheduler.start(appContext) } fun start() { @@ -202,6 +224,9 @@ class AppContainer( if (enabled) { AlertNotifier(appContext, fxRates).ensureChannels() DealAlertScheduler.start(appContext) + // Establish the baseline now rather than an hour from now. It also makes the switch + // give immediate, visible feedback in Settings, which is where the user turns it on. + DealAlertScheduler.enqueueNow(appContext) } else { DealAlertScheduler.stop(appContext) } diff --git a/app/src/main/java/com/discounthunter/android/ui/settings/NotificationPermissionPrompt.kt b/app/src/main/java/com/discounthunter/android/ui/settings/NotificationPermissionPrompt.kt new file mode 100644 index 0000000..9bd1cfe --- /dev/null +++ b/app/src/main/java/com/discounthunter/android/ui/settings/NotificationPermissionPrompt.kt @@ -0,0 +1,121 @@ +package com.discounthunter.android.ui.settings + +import android.Manifest +import android.os.Build +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.res.stringResource +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import com.discounthunter.android.R +import com.discounthunter.android.alerts.AlertNotifier +import com.discounthunter.android.alerts.DealAlertScheduler +import com.discounthunter.android.alerts.NotificationPermissionPolicy +import com.discounthunter.android.di.AppContainer +import kotlinx.coroutines.launch + +/** + * Explains why the app needs to notify, then asks for the permission once. + * + * ## Why this exists + * + * Deal alerts are on by default, and on Android 13 and above the notification permission is denied + * until it is asked for. The app used to ask only when the user turned the switch **on** — but it + * already was on, so a fresh install never asked, and its background checks could never show + * anything. The feature looked enabled and did nothing. + * + * The prompt is deliberately shown after the intro, in the app itself, rather than as a raw system + * dialog on first launch: the system dialog has no room to say *what* the permission is for. It is + * shown once, and "Not now" is remembered. The Settings screen keeps a manual "Allow notifications" + * action, so declining here is not permanent. + */ +@Composable +fun NotificationPermissionPrompt(container: AppContainer) { + val scope = rememberCoroutineScope() + val settings by container.settings.settings.collectAsStateWithLifecycle(initialValue = null) + + var canPost by remember { mutableStateOf(AlertNotifier(container.appContext).canPost()) } + + // The permission can be changed in system settings while the app is in the background. Re-read + // it on every resume so the dialog and the Settings warning reflect reality rather than the + // state they happened to see when they were composed. + val lifecycleOwner = LocalLifecycleOwner.current + DisposableEffect(lifecycleOwner) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_RESUME) { + canPost = AlertNotifier(container.appContext).canPost() + } + } + lifecycleOwner.lifecycle.addObserver(observer) + onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } + } + + val launcher = rememberLauncherForActivityResult( + ActivityResultContracts.RequestPermission(), + ) { granted -> + canPost = AlertNotifier(container.appContext).canPost() + if (granted) { + // The channels may not exist yet if the first check has never run. + AlertNotifier(container.appContext).ensureChannels() + // Check soon rather than waiting for the next alarm: if a sale was detected while the + // permission was missing, the record deliberately still holds it, and this is the + // moment it can finally be announced. + DealAlertScheduler.enqueueNow(container.appContext) + } + } + + val markPrompted: () -> Unit = { + scope.launch { container.settings.setNotificationPermissionPromptShown() } + Unit + } + + val current = settings ?: return + val shouldShow = NotificationPermissionPolicy.shouldPrompt( + apiLevel = Build.VERSION.SDK_INT, + alertsEnabled = current.saleAlertsEnabled, + canPost = canPost, + alreadyPrompted = current.hasPromptedNotificationPermission, + ) + if (!shouldShow) return + + AlertDialog( + onDismissRequest = { markPrompted() }, + title = { Text(stringResource(R.string.alert_permission_title)) }, + text = { + Text( + text = stringResource(R.string.alert_permission_rationale), + style = MaterialTheme.typography.bodyMedium, + ) + }, + confirmButton = { + TextButton( + onClick = { + // Recorded before the system dialog opens, so a configuration change cannot + // show this explanation a second time. + markPrompted() + launcher.launch(Manifest.permission.POST_NOTIFICATIONS) + }, + ) { + Text(stringResource(R.string.alert_permission_allow)) + } + }, + dismissButton = { + TextButton(onClick = { markPrompted() }) { + Text(stringResource(R.string.alert_permission_not_now)) + } + }, + ) +} diff --git a/app/src/main/java/com/discounthunter/android/ui/settings/SettingsScreen.kt b/app/src/main/java/com/discounthunter/android/ui/settings/SettingsScreen.kt index 9d3aa50..b470090 100644 --- a/app/src/main/java/com/discounthunter/android/ui/settings/SettingsScreen.kt +++ b/app/src/main/java/com/discounthunter/android/ui/settings/SettingsScreen.kt @@ -38,6 +38,7 @@ import androidx.compose.material3.TextButton import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -48,6 +49,9 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.discounthunter.android.BuildConfig import androidx.compose.material.icons.outlined.BugReport @@ -55,11 +59,18 @@ import androidx.compose.material.icons.outlined.DeleteForever import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.ButtonDefaults import com.discounthunter.android.R +import com.discounthunter.android.alerts.AlertCheckOutcome +import com.discounthunter.android.alerts.AlertRunStatus +import com.discounthunter.android.alerts.NotificationPermissionPolicy import com.discounthunter.android.core.model.StoreId import com.discounthunter.android.data.settings.AppSettings import com.discounthunter.android.data.settings.CurrencyCode import com.discounthunter.android.data.settings.ThemeMode import com.discounthunter.android.update.UpdateState +import java.time.Instant +import java.time.ZoneId +import java.time.format.DateTimeFormatter +import java.time.format.FormatStyle import kotlin.math.roundToInt /** @@ -107,6 +118,21 @@ fun SettingsScreen( onStoreAppStateChanged() } + // A permission or battery setting can be changed in system settings while this screen is in + // the background. Re-read the things that depend on them when the user comes back, rather than + // showing a stale warning or a stale "last checked" line. + val lifecycleOwner = LocalLifecycleOwner.current + DisposableEffect(lifecycleOwner) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_RESUME) { + viewModel.refreshNotificationPermission() + viewModel.refreshAlertDiagnostics() + } + } + lifecycleOwner.lifecycle.addObserver(observer) + onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } + } + Scaffold( modifier = modifier, topBar = { @@ -247,9 +273,13 @@ fun SettingsScreen( // The switch can be on and the feature still be unable to do anything, because // Android 13 and above need notifications to be granted explicitly. Saying so, and - // offering the one place it can be changed, is the difference between a setting - // that works and a setting that quietly does nothing. - if (state.settings.saleAlertsEnabled && !state.notificationsAllowed) { + // offering both ways to fix it, is the difference between a setting that works and + // a setting that quietly does nothing. + if (NotificationPermissionPolicy.shouldWarn( + alertsEnabled = state.settings.saleAlertsEnabled, + canPost = state.notificationsAllowed, + ) + ) { Spacer(Modifier.height(12.dp)) Text( text = stringResource(R.string.settings_alerts_permission_needed), @@ -257,8 +287,55 @@ fun SettingsScreen( color = MaterialTheme.colorScheme.error, ) Spacer(Modifier.height(8.dp)) - OutlinedButton(onClick = viewModel::openNotificationSettings) { - Text(stringResource(R.string.settings_alerts_open_settings)) + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + // On Android 13 and above the system dialog can still be shown. If the + // user has permanently denied it, Android answers immediately and the + // settings button is the way back. + if (NotificationPermissionPolicy.canRequestFromApp( + apiLevel = Build.VERSION.SDK_INT, + canPost = state.notificationsAllowed, + ) + ) { + OutlinedButton(onClick = requestNotifications) { + Text(stringResource(R.string.settings_alerts_allow)) + } + } + OutlinedButton(onClick = viewModel::openNotificationSettings) { + Text(stringResource(R.string.settings_alerts_open_settings)) + } + } + } + + Spacer(Modifier.height(12.dp)) + AlertLastCheckText(state.alertStatus) + state.nextCheckAt?.let { next -> + Spacer(Modifier.height(2.dp)) + Text( + text = stringResource( + R.string.settings_alerts_next_check, + formatAlertTime(next), + ), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Spacer(Modifier.height(8.dp)) + OutlinedButton(onClick = viewModel::checkAlertsNow) { + Text(stringResource(R.string.settings_alerts_check_now)) + } + + // A device-level restriction, not an app bug: several manufacturers defer even + // exact alarms and periodic work until the app is next opened. The user can only + // fix it if they know it exists. + if (state.settings.saleAlertsEnabled && !state.batteryUnrestricted) { + Spacer(Modifier.height(10.dp)) + Text( + text = stringResource(R.string.settings_alerts_battery_warning), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + TextButton(onClick = viewModel::openBatterySettings) { + Text(stringResource(R.string.settings_alerts_battery_settings)) } } } @@ -528,6 +605,58 @@ fun SettingsScreen( } } +/** + * The result of the last background check, in one line. + * + * "No check has run yet" is a distinct message on purpose: it is the honest answer on a fresh + * install, and it is different from "the last check found nothing". + */ +@Composable +private fun AlertLastCheckText(status: AlertRunStatus?) { + val text = if (status == null) { + stringResource(R.string.settings_alerts_never_checked) + } else { + val outcome = when (status.outcome) { + AlertCheckOutcome.CHECKED -> stringResource( + R.string.settings_alerts_outcome_checked, + status.deals, + status.wishlist, + ) + + AlertCheckOutcome.ANNOUNCED -> stringResource( + R.string.settings_alerts_outcome_announced, + status.announced, + ) + + AlertCheckOutcome.NOTIFICATIONS_BLOCKED -> + stringResource(R.string.settings_alerts_outcome_blocked) + + AlertCheckOutcome.FEED_EMPTY -> + stringResource(R.string.settings_alerts_outcome_feed_empty) + + AlertCheckOutcome.MONITORING_OFF -> + stringResource(R.string.settings_alerts_outcome_off) + + AlertCheckOutcome.FAILED -> + stringResource(R.string.settings_alerts_outcome_failed) + } + stringResource(R.string.settings_alerts_last_check, formatAlertTime(status.checkedAt), outcome) + } + Text( + text = text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + +/** Formats an epoch-millis timestamp in the device's locale and time zone. */ +private fun formatAlertTime(epochMillis: Long): String = runCatching { + DateTimeFormatter + .ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT) + .withZone(ZoneId.systemDefault()) + .format(Instant.ofEpochMilli(epochMillis)) +}.getOrDefault(epochMillis.toString()) + @Composable private fun SettingsCard( title: String, diff --git a/app/src/main/java/com/discounthunter/android/ui/settings/SettingsViewModel.kt b/app/src/main/java/com/discounthunter/android/ui/settings/SettingsViewModel.kt index b8948b7..12ed4eb 100644 --- a/app/src/main/java/com/discounthunter/android/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/com/discounthunter/android/ui/settings/SettingsViewModel.kt @@ -2,10 +2,14 @@ package com.discounthunter.android.ui.settings import android.content.Context import android.content.Intent +import android.os.PowerManager import androidx.core.content.FileProvider import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.discounthunter.android.alerts.AlertNotifier +import com.discounthunter.android.alerts.AlertRunStatus +import com.discounthunter.android.alerts.AlertStatusStore +import com.discounthunter.android.alerts.DealAlertScheduler import com.discounthunter.android.core.model.StoreId import com.discounthunter.android.data.settings.AppSettings import com.discounthunter.android.data.settings.CurrencyCode @@ -68,6 +72,18 @@ data class SettingsUiState( * while this is false, which is exactly the state that makes the feature look broken. */ val notificationsAllowed: Boolean = true, + /** The result of the last background deal check, or null when none has run. */ + val alertStatus: AlertRunStatus? = null, + /** When the next punctual check is due, or null when no alarm is armed. */ + val nextCheckAt: Long? = null, + /** + * True when Android is not restricting the app's background work. + * + * On several manufacturers' builds the periodic worker and even the alarm are deferred until + * the app is opened when battery optimisation is on. This is a property of the device, not of + * the app, but the user can only fix it if they are told. + */ + val batteryUnrestricted: Boolean = true, ) /** @@ -88,6 +104,9 @@ class SettingsViewModel( private val deleting = MutableStateFlow(false) private val detectedApps = MutableStateFlow(StoreId.MAJOR.associateWith { false }) private val notificationsAllowed = MutableStateFlow(true) + private val alertStatus = MutableStateFlow(null) + private val nextCheckAt = MutableStateFlow(null) + private val batteryUnrestricted = MutableStateFlow(true) /** * The updater. @@ -121,6 +140,7 @@ class SettingsViewModel( val clearing: Boolean, val deleting: Boolean, val notificationsAllowed: Boolean, + val alertStatus: AlertRunStatus?, ) private val localFlags = combine( @@ -128,15 +148,18 @@ class SettingsViewModel( clearing, deleting, notificationsAllowed, - ) { size, isClearing, isDeleting, allowed -> - LocalFlags(size, isClearing, isDeleting, allowed) + alertStatus, + ) { size, isClearing, isDeleting, allowed, status -> + LocalFlags(size, isClearing, isDeleting, allowed, status) } val uiState: StateFlow = combine( settingsRepository.settings, detectedApps, localFlags, - ) { settings, apps, flags -> + batteryUnrestricted, + nextCheckAt, + ) { settings, apps, flags, battery, nextCheck -> SettingsUiState( settings = settings, cacheSizeBytes = flags.cacheSize, @@ -144,6 +167,9 @@ class SettingsViewModel( isDeletingData = flags.deleting, storeApps = apps, notificationsAllowed = flags.notificationsAllowed, + alertStatus = flags.alertStatus, + nextCheckAt = nextCheck, + batteryUnrestricted = battery, ) }.stateIn( scope = viewModelScope, @@ -157,6 +183,12 @@ class SettingsViewModel( .launchIn(viewModelScope) refreshStoreApps() refreshNotificationPermission() + refreshAlertDiagnostics() + // The worker can finish while this screen is open. The process-wide flow means the status + // line updates then, without the user having to leave and come back. + viewModelScope.launch { + AlertStatusStore.latest.collect { status -> alertStatus.value = status } + } } // ------------------------------------------------------------------ actions @@ -195,6 +227,7 @@ class SettingsViewModel( fun setSaleAlertsEnabled(enabled: Boolean) = viewModelScope.launch { container.setSaleAlertsEnabled(enabled) refreshNotificationPermission() + refreshAlertDiagnostics() } /** @@ -221,6 +254,55 @@ class SettingsViewModel( notificationsAllowed.value = AlertNotifier(container.appContext).canPost() } + /** + * Re-reads the last background check, the next alarm and the device's battery policy. + * + * Called when the screen appears, on resume (the user may have changed a system setting while + * they were away), and after the switch is toggled. These are deliberately not a single + * persisted setting: two come from the scheduler and the platform, and one from a file the + * worker wrote. + */ + fun refreshAlertDiagnostics() { + nextCheckAt.value = DealAlertScheduler.nextAlarmAt(container.appContext) + val power = container.appContext.getSystemService(PowerManager::class.java) + batteryUnrestricted.value = + power?.isIgnoringBatteryOptimizations(container.appContext.packageName) ?: true + viewModelScope.launch { + alertStatus.value = AlertStatusStore(container.alertStatusFile).load() ?: alertStatus.value + } + } + + /** + * Queues a deal check immediately. + * + * The result appears in the status line once the worker has run, which is usually a few + * seconds. This exists so a user who is wondering whether the feature works does not have to + * wait an hour, or guess from the absence of a notification. + */ + fun checkAlertsNow() { + DealAlertScheduler.enqueueNow(container.appContext) + AppLog.i("Alerts: a check was requested from Settings") + } + + /** + * Opens the screen where the user can exempt the app from battery optimisation. + * + * The app cannot grant this itself, and it should not: the permission that would allow a + * one-tap request is reserved for a narrow set of app types. Opening the list is honest and + * leaves the decision with the user. If a manufacturer has hidden that screen, the app's own + * details page is the fallback, because it has a battery entry on most builds. + */ + fun openBatterySettings() { + val context = container.appContext + val optimization = Intent(android.provider.Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + if (runCatching { context.startActivity(optimization) }.isSuccess) return + val details = Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS) + .setData(android.net.Uri.fromParts("package", context.packageName, null)) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + runCatching { context.startActivity(details) } + } + // ------------------------------------------------------------------ updates /** Checks the official release feed for a newer version. */ diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 846cbd2..9b777d7 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -127,8 +127,25 @@ Deal alerts Tell me when a saved game goes on sale, and when a game becomes free to keep. Checked about once an hour in the background, including when the app is closed. Only changes are announced: a game that is still on sale tomorrow is not announced again. A game that is already on sale when you turn this on is not announced either — the check starts from now. - Notifications are blocked for Discount Hunter, so alerts cannot be shown. Allow them in the system settings. + Notifications are blocked for Discount Hunter, so alerts cannot be shown. Allow them here, or in the system settings. Open settings + Allow notifications + Check now + No background check has run yet. + Last check: %1$s — %2$s + found nothing new (%1$d deals, %2$d saved) + posted %1$d notification(s) + notifications are blocked, so the check was skipped + the stores returned no deals, so there was nothing to compare + deal alerts were off, so the check was skipped + the check failed and will be retried + Next check around %1$s. + Android\'s battery optimisation can delay background checks. If alerts arrive late or not at all, allow unrestricted battery use for Discount Hunter. + Battery settings + Get notified about deals + Discount Hunter can tell you when a saved game goes on sale, and when a game becomes free to keep — even while the app is closed. Android needs your permission to show those notifications. + Allow notifications + Not now Sales on your wishlist A game you saved has started being discounted. Free games diff --git a/app/src/test/java/com/discounthunter/android/alerts/AlarmScheduleTest.kt b/app/src/test/java/com/discounthunter/android/alerts/AlarmScheduleTest.kt new file mode 100644 index 0000000..874044a --- /dev/null +++ b/app/src/test/java/com/discounthunter/android/alerts/AlarmScheduleTest.kt @@ -0,0 +1,104 @@ +package com.discounthunter.android.alerts + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * When the next alarm is armed. + * + * This rule exists because of a real background failure: `AppContainer.start()` ran on every + * process creation, and each run pushed the alarm an hour into the future. WorkManager creates a + * process for its periodic worker, so the alarm was reset by the very thing that was supposed to + * be its backstop. On a phone whose battery manager defers periodic work, that left no punctual + * path at all — which is exactly "notifications do not work when the app is closed". + */ +class AlarmScheduleTest { + + private val interval = DealAlertScheduler.CHECK_INTERVAL_MINUTES * 60_000L + + /** A realistic epoch-millis instant: negative values are not wall-clock times. */ + private val now = 1_794_000_000_000L + + @Test + fun `an alarm that is not pending is armed`() { + assertTrue( + AlarmSchedule.shouldArm( + now = now, + nextAlarmAt = 0L, + hasPendingAlarm = false, + force = false, + intervalMillis = interval, + ), + ) + } + + @Test + fun `an alarm that is already armed is left alone`() { + assertFalse( + AlarmSchedule.shouldArm( + now = now, + nextAlarmAt = now + 10 * 60_000L, + hasPendingAlarm = true, + force = false, + intervalMillis = interval, + ), + ) + } + + @Test + fun `a slightly late alarm is not reset`() { + // Doze can deliver an alarm well after its due time. Re-arming then would push it another + // full interval away, which is the bug, not the fix. + assertFalse( + AlarmSchedule.shouldArm( + now = now, + nextAlarmAt = now - interval, + hasPendingAlarm = true, + force = false, + intervalMillis = interval, + ), + ) + } + + @Test + fun `an alarm that is many intervals overdue is re-armed`() { + assertTrue( + AlarmSchedule.shouldArm( + now = now, + nextAlarmAt = now - (AlarmSchedule.STALE_AFTER_INTERVALS + 1) * interval, + hasPendingAlarm = true, + force = false, + intervalMillis = interval, + ), + ) + } + + @Test + fun `a forced arm always happens`() { + assertTrue( + AlarmSchedule.shouldArm( + now = now, + nextAlarmAt = now + interval, + hasPendingAlarm = true, + force = true, + intervalMillis = interval, + ), + ) + } + + @Test + fun `a pending alarm with no stored time is left alone`() { + // The platform has it, and the receiver will arm the next one when it fires. Re-arming on + // unknown information would reintroduce the push-back this rule exists to prevent. + assertFalse( + AlarmSchedule.shouldArm( + now = now, + nextAlarmAt = 0L, + hasPendingAlarm = true, + force = false, + intervalMillis = interval, + ), + ) + } +} diff --git a/app/src/test/java/com/discounthunter/android/alerts/AlertDeliveryPolicyTest.kt b/app/src/test/java/com/discounthunter/android/alerts/AlertDeliveryPolicyTest.kt new file mode 100644 index 0000000..13ef99d --- /dev/null +++ b/app/src/test/java/com/discounthunter/android/alerts/AlertDeliveryPolicyTest.kt @@ -0,0 +1,60 @@ +package com.discounthunter.android.alerts + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * Whether a check may record what it saw as announced. + * + * If the app detected a sale but could not post the notification, the record must not advance: + * otherwise the news is consumed silently and granting the permission later brings nothing back. + */ +class AlertDeliveryPolicyTest { + + @Test + fun `nothing to announce means the state is still recorded`() { + assertTrue( + AlertDeliveryPolicy.shouldAdvanceState( + hasAnythingToAnnounce = false, + posted = 0, + previouslyInitialised = true, + ), + ) + } + + @Test + fun `a posted announcement advances the state`() { + assertTrue( + AlertDeliveryPolicy.shouldAdvanceState( + hasAnythingToAnnounce = true, + posted = 1, + previouslyInitialised = true, + ), + ) + } + + @Test + fun `an announcement that could not be posted is left pending`() { + assertFalse( + AlertDeliveryPolicy.shouldAdvanceState( + hasAnythingToAnnounce = true, + posted = 0, + previouslyInitialised = true, + ), + ) + } + + @Test + fun `the first run establishes a baseline even when nothing was posted`() { + // The first run has no announcements by definition. Without the baseline, every later run + // would also look like a first run and announce nothing. + assertTrue( + AlertDeliveryPolicy.shouldAdvanceState( + hasAnythingToAnnounce = false, + posted = 0, + previouslyInitialised = false, + ), + ) + } +} diff --git a/app/src/test/java/com/discounthunter/android/alerts/AlertStatusStoreTest.kt b/app/src/test/java/com/discounthunter/android/alerts/AlertStatusStoreTest.kt new file mode 100644 index 0000000..6106df9 --- /dev/null +++ b/app/src/test/java/com/discounthunter/android/alerts/AlertStatusStoreTest.kt @@ -0,0 +1,115 @@ +package com.discounthunter.android.alerts + +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Test +import java.io.File +import java.nio.file.Files + +/** + * The record of the last background check. + * + * This is the thing that turns "notifications are not working" into a specific answer: did the + * check run, and what did it do? It therefore has to survive a process death, read a missing file + * as "no check yet" rather than a success, and never crash the Settings screen on a corrupt one. + */ +class AlertStatusStoreTest { + + @Test + fun `a record round-trips through its stored form`() { + val status = AlertRunStatus( + checkedAt = 1_794_000_000_000L, + outcome = AlertCheckOutcome.ANNOUNCED, + announced = 2, + deals = 137, + wishlist = 4, + message = "fine", + ) + assertEquals(status, AlertStatusCodec.parse(AlertStatusCodec.serialize(status))) + } + + @Test + fun `every outcome round-trips`() { + for (outcome in AlertCheckOutcome.entries) { + val status = AlertRunStatus( + checkedAt = 1L, + outcome = outcome, + ) + assertEquals(outcome, AlertStatusCodec.parse(AlertStatusCodec.serialize(status))?.outcome) + } + } + + @Test + fun `a malformed record is rejected rather than guessed`() { + assertNull(AlertStatusCodec.parse("not json")) + assertNull(AlertStatusCodec.parse("{}")) + assertNull(AlertStatusCodec.parse("""{"checkedAt":1}""")) + assertNull(AlertStatusCodec.parse("""{"checkedAt":1,"outcome":"NOT_AN_OUTCOME"}""")) + } + + @Test + fun `missing counters default to zero`() { + val status = AlertStatusCodec.parse("""{"checkedAt":123,"outcome":"CHECKED"}""") + assertEquals(123L, status?.checkedAt) + assertEquals(0, status?.announced) + assertEquals(0, status?.deals) + assertEquals(0, status?.wishlist) + } + + @Test + fun `a very long diagnostic message is truncated`() { + val status = AlertRunStatus( + checkedAt = 1L, + outcome = AlertCheckOutcome.FAILED, + message = "x".repeat(10_000), + ) + val parsed = AlertStatusCodec.parse(AlertStatusCodec.serialize(status)) + assertEquals(300, parsed?.message?.length) + } + + @Test + fun `a missing file reads as no check`() = runBlocking { + val directory = Files.createTempDirectory("dh-alert-status-missing").toFile() + try { + assertNull(AlertStatusStore(File(directory, "alerts/status.json")).load()) + } finally { + directory.deleteRecursively() + } + } + + @Test + fun `recording a check makes it readable again`() = runBlocking { + val directory = Files.createTempDirectory("dh-alert-status-write").toFile() + try { + val file = File(directory, "alerts/status.json") + val store = AlertStatusStore(file) + val status = AlertRunStatus( + checkedAt = 1_794_000_000_000L, + outcome = AlertCheckOutcome.CHECKED, + deals = 60, + wishlist = 3, + ) + store.record(status) + assertEquals(status, store.load()) + // The atomic write's temporary sibling must not survive. + assertFalse(File(directory, "alerts/status.json.tmp").exists()) + } finally { + directory.deleteRecursively() + } + } + + @Test + fun `a corrupt file reads as no check rather than throwing`() = runBlocking { + val directory = Files.createTempDirectory("dh-alert-status-corrupt").toFile() + try { + val file = File(directory, "alerts/status.json") + file.parentFile?.mkdirs() + file.writeText("{ this is not json") + assertNull(AlertStatusStore(file).load()) + } finally { + directory.deleteRecursively() + } + } +} diff --git a/app/src/test/java/com/discounthunter/android/alerts/NotificationPermissionPolicyTest.kt b/app/src/test/java/com/discounthunter/android/alerts/NotificationPermissionPolicyTest.kt new file mode 100644 index 0000000..3c4a848 --- /dev/null +++ b/app/src/test/java/com/discounthunter/android/alerts/NotificationPermissionPolicyTest.kt @@ -0,0 +1,92 @@ +package com.discounthunter.android.alerts + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * When the notification permission prompt is shown. + * + * The defect this guards against: deal alerts default to on, but on Android 13+ the notification + * permission starts denied, and the app only asked when the switch was turned *on*. A fresh + * install therefore never asked, and its background checks could never show anything. + */ +class NotificationPermissionPolicyTest { + + @Test + fun `a fresh install with alerts on asks once`() { + assertTrue( + NotificationPermissionPolicy.shouldPrompt( + apiLevel = 33, + alertsEnabled = true, + canPost = false, + alreadyPrompted = false, + ), + ) + } + + @Test + fun `a user who has already been asked is not asked again`() { + assertFalse( + NotificationPermissionPolicy.shouldPrompt( + apiLevel = 33, + alertsEnabled = true, + canPost = false, + alreadyPrompted = true, + ), + ) + } + + @Test + fun `nothing is asked when notifications already work`() { + assertFalse( + NotificationPermissionPolicy.shouldPrompt( + apiLevel = 34, + alertsEnabled = true, + canPost = true, + alreadyPrompted = false, + ), + ) + } + + @Test + fun `nothing is asked when the feature is off`() { + assertFalse( + NotificationPermissionPolicy.shouldPrompt( + apiLevel = 33, + alertsEnabled = false, + canPost = false, + alreadyPrompted = false, + ), + ) + } + + @Test + fun `nothing is asked below Android 13`() { + // There is no runtime notification permission before API 33; the permission is granted at + // install time, and the only way to remove it is in system settings. + assertFalse( + NotificationPermissionPolicy.shouldPrompt( + apiLevel = 32, + alertsEnabled = true, + canPost = false, + alreadyPrompted = false, + ), + ) + } + + @Test + fun `the system dialog can be shown on Android 13 and above`() { + assertTrue(NotificationPermissionPolicy.canRequestFromApp(33, canPost = false)) + assertTrue(NotificationPermissionPolicy.canRequestFromApp(35, canPost = false)) + assertFalse(NotificationPermissionPolicy.canRequestFromApp(33, canPost = true)) + assertFalse(NotificationPermissionPolicy.canRequestFromApp(32, canPost = false)) + } + + @Test + fun `the settings warning is exactly the unusable state`() { + assertTrue(NotificationPermissionPolicy.shouldWarn(alertsEnabled = true, canPost = false)) + assertFalse(NotificationPermissionPolicy.shouldWarn(alertsEnabled = true, canPost = true)) + assertFalse(NotificationPermissionPolicy.shouldWarn(alertsEnabled = false, canPost = false)) + } +} diff --git a/docs/ENGINEERING.md b/docs/ENGINEERING.md index b990266..792a810 100644 --- a/docs/ENGINEERING.md +++ b/docs/ENGINEERING.md @@ -398,6 +398,24 @@ Run a single suite: a call R8 cannot see, so R8 removed it. Every debug run passed; the crash existed only in the build that would have been shipped. Fixed with two keep rules, and the release APK is now installed and launched on a device before the work is called done. +49. **A fresh install could never show a notification.** Deal alerts default to on, but the only + `POST_NOTIFICATIONS` request was in the switch's off-to-on handler, which a fresh install never + reaches. On Android 13+ the permission starts denied, so the check ran, the record advanced and + every notification was dropped. A one-time explanation after the intro now asks, and Settings + keeps an Allow notifications action. +50. **Every process start pushed the alarm an hour into the future.** `AppContainer.start()` called + `scheduleAlarm()` with `FLAG_UPDATE_CURRENT`, including the process WorkManager creates for its + own worker. On a device woken often enough the punctual alarm never fired. The due time is now + persisted, an armed alarm is left alone, and only a firing, reboot, app replacement or explicit + on/off change re-arms it (`AlarmSchedule.shouldArm`). +51. **A change detected while notifications were blocked was recorded as delivered.** The watch + state advanced even when `announce()` posted nothing, so granting the permission later brought + nothing back. `AlertDeliveryPolicy.shouldAdvanceState` now requires an actual post, except on + the first-run baseline, and the worker checks `canPost()` before fetching. +52. **Free games were skipped when the wishlist was empty.** `SaleDetector` announces them without a + wishlist, but the worker returned early. The early return is gone. +53. **"Delete all app data" left the alert records behind.** It now clears the watch state and the + status record, resets the in-memory status, and restarts the default schedule. Full write-up with the reasoning in [DEV_NOTES.md](DEV_NOTES.md).