Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
69 changes: 69 additions & 0 deletions DEV_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,75 @@ The fix is two keep rules in `proguard-rules.pro`:
-keep class * extends androidx.room.RoomDatabase { <init>(); }
-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
Expand Down
17 changes: 9 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,17 @@ games to watch their prices.
<img src="docs/screenshots/08-diagnostics.png" width="32%" alt="Settings, including log export" />
</p>

## 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

Expand Down
4 changes: 2 additions & 2 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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. */
Expand Down
Original file line number Diff line number Diff line change
@@ -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
}
Original file line number Diff line number Diff line change
@@ -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<AlertRunStatus?>(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<AlertRunStatus?> = _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
}
Loading
Loading