Reminder subsystem: exact alarms, escalation, boot re-arm — verified on emulator

Milestone 4. AlarmScheduler is the only AlarmManager writer; one stable
PendingIntent requestCode per dose-time means re-arming replaces and can
never stack (the no-drift invariant is OS-enforced). DoseAlarmReceiver
handles both occurrence and escalation alarms idempotently and always
re-arms the next occurrence before anything else so the chain can't
break. nagCount lives in dose_log so the ~6-nag cap survives reboot.
SCHEDULE_EXACT_ALARM added maxSdk 32 (USE_EXACT_ALARM is 33+ only).

Emulator-verified (API 35): exact alarm armed (window=0,
policy_permission), fired on time, HIGH notification with Tatt/Utsett,
escalation armed +10 min, next day re-armed, Tatt → TAKEN + inventory
10→9 + escalation cancelled, reboot → BootReceiver re-armed everything.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Ole-Morten Duesund 2026-06-10 13:48:39 +02:00
commit 46a5d7e98e
16 changed files with 714 additions and 14 deletions

View file

@ -0,0 +1,140 @@
package no.naiv.meddetsamme.alarm
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.ZoneId
import no.naiv.meddetsamme.data.MedDatabase
import no.naiv.meddetsamme.domain.ScheduleEngine
/**
* The only writer of AlarmManager state. Invariant: at most ONE pending alarm
* per dose-time (its next occurrence) plus at most one escalation alarm per
* unresolved dose-log. Everything is recomputed from the DB via the pure
* engine reboot, update, Taken and Snooze all just call back in here, so
* alarm state can never drift from schedule state.
*/
class AlarmScheduler(private val context: Context) {
companion object {
/** Escalation contract (CLAUDE.md): re-nag every 10 min, ~6 nags / ~1 h. */
const val NAG_INTERVAL_MINUTES = 10L
const val NAG_CAP = 6
const val SNOOZE_MINUTES = 15L
/** Daily supply/renewal check; lateness is harmless so it's inexact. */
val SUPPLY_CHECK_TIME: LocalTime = LocalTime.of(10, 0)
private const val SUPPLY_REQUEST_CODE = 9_001
}
private val alarmManager = context.getSystemService(AlarmManager::class.java)
private val zone: ZoneId get() = ZoneId.systemDefault()
/**
* Exact when permitted, inexact otherwise a slightly late reminder still
* beats a crash, and canScheduleExactAlarms() can be revoked at runtime.
* On API 33+ USE_EXACT_ALARM makes this effectively always true.
*/
private fun setAlarm(triggerAtMillis: Long, operation: PendingIntent) {
val canExact = Build.VERSION.SDK_INT < 31 || alarmManager.canScheduleExactAlarms()
if (canExact) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation)
} else {
alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation)
}
}
// ---- dose-time occurrence alarms --------------------------------------
private fun doseIntent(doseTimeId: Long, scheduledAtMillis: Long): PendingIntent =
PendingIntent.getBroadcast(
context,
doseTimeId.mod(Int.MAX_VALUE.toLong()).toInt(),
Intent(context, DoseAlarmReceiver::class.java)
.putExtra(DoseAlarmReceiver.EXTRA_DOSE_TIME_ID, doseTimeId)
.putExtra(DoseAlarmReceiver.EXTRA_SCHEDULED_AT, scheduledAtMillis),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
/** Arm (or re-arm) the single alarm for one dose-time's next occurrence. */
suspend fun armDoseTime(doseTimeId: Long, after: LocalDateTime = LocalDateTime.now()) {
val db = MedDatabase.get(context)
val doseTime = db.doseTimeDao().getById(doseTimeId) ?: return
val med = db.medicationDao().getById(doseTime.medId)
if (med == null || !med.active) {
cancelDoseTime(doseTimeId)
return
}
val next = ScheduleEngine.nextOccurrence(doseTime, after)
if (next == null) {
cancelDoseTime(doseTimeId)
return
}
val millis = next.atZone(zone).toInstant().toEpochMilli()
// Same requestCode per dose-time + FLAG_UPDATE_CURRENT = the invariant:
// re-arming replaces, it never stacks.
setAlarm(millis, doseIntent(doseTimeId, millis))
}
fun cancelDoseTime(doseTimeId: Long) {
alarmManager.cancel(doseIntent(doseTimeId, 0))
}
/** Full rebuild from DB: boot, app update, schedule edits, app start. */
suspend fun armAll() {
val db = MedDatabase.get(context)
db.doseTimeDao().getAllForActiveMeds().forEach { armDoseTime(it.id) }
armSupplyCheck()
// Resume nagging for doses that were unresolved when the device died.
db.doseLogDao().getUnresolved().forEach { log ->
if (log.nagCount < NAG_CAP) armEscalation(log.id, delayMinutes = 1)
}
}
// ---- escalation alarms -------------------------------------------------
private fun escalationIntent(logId: Long): PendingIntent =
PendingIntent.getBroadcast(
context,
// Offset keeps escalation requestCodes from colliding with dose-time codes.
(logId.mod((Int.MAX_VALUE / 2).toLong())).toInt() + Int.MAX_VALUE / 2,
Intent(context, DoseAlarmReceiver::class.java)
.putExtra(DoseAlarmReceiver.EXTRA_LOG_ID, logId),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
/** One escalation alarm per unresolved log; re-arming replaces. */
fun armEscalation(logId: Long, delayMinutes: Long = NAG_INTERVAL_MINUTES) {
val triggerAt = System.currentTimeMillis() + delayMinutes * 60_000
setAlarm(triggerAt, escalationIntent(logId))
}
fun cancelEscalation(logId: Long) {
alarmManager.cancel(escalationIntent(logId))
}
// ---- daily supply / renewal check --------------------------------------
private fun supplyIntent(): PendingIntent =
PendingIntent.getBroadcast(
context,
SUPPLY_REQUEST_CODE,
Intent(context, SupplyCheckReceiver::class.java),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
/** Inexact daily check at ~10:00; the receiver re-arms the next one. */
fun armSupplyCheck() {
var next = LocalDateTime.of(java.time.LocalDate.now(), SUPPLY_CHECK_TIME)
if (!next.isAfter(LocalDateTime.now())) next = next.plusDays(1)
alarmManager.setAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
next.atZone(zone).toInstant().toEpochMilli(),
supplyIntent(),
)
}
}

View file

@ -0,0 +1,29 @@
package no.naiv.meddetsamme.alarm
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.PowerManager
import android.provider.Settings
/**
* Battery-optimisation ("Doze whitelist") exemption brief decision #4: the
* single biggest cause of dropped reminders on aggressive OEMs. The UI shows a
* one-time prompt built on these helpers; we never nag about it repeatedly.
*/
object BatteryOptimization {
fun isExempt(context: Context): Boolean =
context.getSystemService(PowerManager::class.java)
.isIgnoringBatteryOptimizations(context.packageName)
/**
* Direct request dialog. Allowed by policy for alarm/reminder apps where
* timing is core functionality which is this app's entire reason to exist.
*/
fun requestExemptionIntent(context: Context): Intent =
Intent(
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
Uri.parse("package:${context.packageName}"),
)
}

View file

@ -0,0 +1,31 @@
package no.naiv.meddetsamme.alarm
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
/**
* AlarmManager forgets everything on reboot, and an app update kills pending
* intents pointing at old code. Both events land here; the fix is the same:
* rebuild all alarms from the DB (brief decision #3).
*/
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
when (intent.action) {
Intent.ACTION_BOOT_COMPLETED, Intent.ACTION_MY_PACKAGE_REPLACED -> Unit
else -> return
}
val pending = goAsync()
CoroutineScope(Dispatchers.IO).launch {
try {
AlarmScheduler(context).armAll()
} finally {
pending.finish()
}
}
}
}

View file

@ -0,0 +1,72 @@
package no.naiv.meddetsamme.alarm
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import no.naiv.meddetsamme.data.DoseStatus
import no.naiv.meddetsamme.data.MedDatabase
import no.naiv.meddetsamme.notify.Notifications
/**
* Handles the notification actions (and later, the same actions from the UI).
*
* Contract (CLAUDE.md, load-bearing):
* - Taken TAKEN, decrement inventory by the *logged* amount, stop escalating.
* - Snooze SNOOZED, next nag in 15 min, keeps escalating (and counting) after.
* - Skip SKIPPED, stop escalating, no inventory change.
*/
class DoseActionReceiver : BroadcastReceiver() {
companion object {
const val ACTION_TAKEN = "no.naiv.meddetsamme.action.TAKEN"
const val ACTION_SNOOZE = "no.naiv.meddetsamme.action.SNOOZE"
const val ACTION_SKIP = "no.naiv.meddetsamme.action.SKIP"
const val EXTRA_LOG_ID = "logId"
}
override fun onReceive(context: Context, intent: Intent) {
val logId = intent.getLongExtra(EXTRA_LOG_ID, -1)
if (logId < 0) return
val action = intent.action ?: return
val pending = goAsync()
CoroutineScope(Dispatchers.IO).launch {
try {
handle(context, action, logId)
} finally {
pending.finish()
}
}
}
private suspend fun handle(context: Context, action: String, logId: Long) {
val db = MedDatabase.get(context)
val scheduler = AlarmScheduler(context)
val log = db.doseLogDao().getById(logId) ?: return
val now = System.currentTimeMillis()
when (action) {
ACTION_TAKEN -> {
// Idempotence: double-tap on a laggy notification must not
// decrement stock twice.
if (log.status == DoseStatus.TAKEN) return
db.doseLogDao().setStatus(logId, DoseStatus.TAKEN, now)
db.medicationDao().decrementInventory(log.medId, log.amount)
scheduler.cancelEscalation(logId)
Notifications.cancel(context, Notifications.doseNotificationId(logId))
}
ACTION_SNOOZE -> {
db.doseLogDao().setStatus(logId, DoseStatus.SNOOZED, now)
scheduler.armEscalation(logId, delayMinutes = AlarmScheduler.SNOOZE_MINUTES)
Notifications.cancel(context, Notifications.doseNotificationId(logId))
}
ACTION_SKIP -> {
db.doseLogDao().setStatus(logId, DoseStatus.SKIPPED, now)
scheduler.cancelEscalation(logId)
Notifications.cancel(context, Notifications.doseNotificationId(logId))
}
}
}
}

View file

@ -0,0 +1,109 @@
package no.naiv.meddetsamme.alarm
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import no.naiv.meddetsamme.data.DoseLog
import no.naiv.meddetsamme.data.DoseStatus
import no.naiv.meddetsamme.data.MedDatabase
import no.naiv.meddetsamme.notify.Notifications
/**
* Fires for both alarm kinds:
* - occurrence alarm (EXTRA_DOSE_TIME_ID + EXTRA_SCHEDULED_AT): creates the
* PENDING log, notifies, starts escalation, and re-arms the next occurrence.
* - escalation alarm (EXTRA_LOG_ID): re-nags an unresolved log until the cap.
*
* Both paths are idempotent: a duplicate delivery finds existing state and
* does nothing harmful important because AlarmManager redelivery and boot
* re-arming can overlap.
*/
class DoseAlarmReceiver : BroadcastReceiver() {
companion object {
const val EXTRA_DOSE_TIME_ID = "doseTimeId"
const val EXTRA_SCHEDULED_AT = "scheduledAt"
const val EXTRA_LOG_ID = "logId"
}
override fun onReceive(context: Context, intent: Intent) {
val pending = goAsync() // keep the process alive for the DB round-trip
CoroutineScope(Dispatchers.IO).launch {
try {
val logId = intent.getLongExtra(EXTRA_LOG_ID, -1)
if (logId >= 0) {
escalate(context, logId)
} else {
fireOccurrence(
context,
intent.getLongExtra(EXTRA_DOSE_TIME_ID, -1),
intent.getLongExtra(EXTRA_SCHEDULED_AT, -1),
)
}
} finally {
pending.finish()
}
}
}
private suspend fun fireOccurrence(context: Context, doseTimeId: Long, scheduledAt: Long) {
if (doseTimeId < 0 || scheduledAt < 0) return
val db = MedDatabase.get(context)
val scheduler = AlarmScheduler(context)
// ALWAYS arm the next occurrence first — even if this one turns out to be
// stale, the chain must never break.
scheduler.armDoseTime(doseTimeId)
val doseTime = db.doseTimeDao().getById(doseTimeId) ?: return
val med = db.medicationDao().getById(doseTime.medId) ?: return
if (!med.active) return
val existing = db.doseLogDao().getForOccurrence(doseTimeId, scheduledAt)
val log = when {
existing == null -> {
val id = db.doseLogDao().insert(
DoseLog(
medId = med.id,
doseTimeId = doseTimeId,
scheduledAtMillis = scheduledAt,
amount = doseTime.amount,
),
)
db.doseLogDao().getById(id)!!
}
// Already resolved (e.g. taken early from the UI) — no notification.
existing.status == DoseStatus.TAKEN || existing.status == DoseStatus.SKIPPED -> return
else -> existing
}
Notifications.post(
context,
Notifications.doseNotificationId(log.id),
Notifications.buildDoseNotification(context, med, log),
)
if (log.nagCount < AlarmScheduler.NAG_CAP) scheduler.armEscalation(log.id)
}
private suspend fun escalate(context: Context, logId: Long) {
val db = MedDatabase.get(context)
val log = db.doseLogDao().getById(logId) ?: return
// Only unresolved doses nag. TAKEN/SKIPPED here means the cancel raced us.
if (log.status != DoseStatus.PENDING && log.status != DoseStatus.SNOOZED) return
if (log.nagCount >= AlarmScheduler.NAG_CAP) return
val med = db.medicationDao().getById(log.medId) ?: return
val nagged = log.copy(nagCount = log.nagCount + 1)
db.doseLogDao().setNagCount(logId, nagged.nagCount)
Notifications.post(
context,
Notifications.doseNotificationId(logId),
Notifications.buildDoseNotification(context, med, nagged),
)
if (nagged.nagCount < AlarmScheduler.NAG_CAP) AlarmScheduler(context).armEscalation(logId)
}
}

View file

@ -0,0 +1,59 @@
package no.naiv.meddetsamme.alarm
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import java.time.LocalDate
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import no.naiv.meddetsamme.data.MedDatabase
import no.naiv.meddetsamme.domain.ScheduleEngine
import no.naiv.meddetsamme.notify.Notifications
/**
* Daily derived-state check: low stock (inventory ÷ scheduled rate) and
* prescription renewal (rx expiry, independent of stock decision #9).
* One digest notification, not one per med.
*/
class SupplyCheckReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val pending = goAsync()
CoroutineScope(Dispatchers.IO).launch {
try {
check(context)
} finally {
AlarmScheduler(context).armSupplyCheck() // chain the next daily check
pending.finish()
}
}
}
private suspend fun check(context: Context) {
val db = MedDatabase.get(context)
val today = LocalDate.now()
val lines = mutableListOf<String>()
for (med in db.medicationDao().getActive()) {
val doseTimes = db.doseTimeDao().getForMed(med.id)
val rate = ScheduleEngine.dailyConsumption(doseTimes)
if (ScheduleEngine.needsRefill(med.inventoryUnits, rate, med.lowStockLeadDays)) {
val days = ScheduleEngine.daysOfSupply(med.inventoryUnits, rate)
lines += "${med.name}: lager for ${days?.toInt() ?: 0} dager"
}
if (ScheduleEngine.needsRenewal(med.rxExpiryEpochDay, today)) {
val expired = med.rxExpiryEpochDay!! < today.toEpochDay()
lines += if (expired) "${med.name}: resept utløpt" else "${med.name}: resept må fornyes"
}
}
if (lines.isNotEmpty()) {
Notifications.post(
context,
Notifications.SUPPLY_NOTIFICATION_ID,
Notifications.buildSupplyNotification(context, lines),
)
}
}
}