Persistent reminders: re-post by delete intent only, survive reboot, keep post time (#100)

This commit is contained in:
makiolaj committed 2026-11-16 19:10:10 +01:00
1 parent 5c619b8de9
commit a67d43edda
7 files changed
+183 -39

No files matched your search

@@ -5,9 +5,12 @@ import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import dagger.hilt.android.AndroidEntryPoint
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.data.tasks.StartupGate
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import javax.inject.Inject
@@ -21,6 +24,9 @@ class BootReceiver : BroadcastReceiver() {
@Inject lateinit var scheduler: ReminderScheduler
@Inject lateinit var snoozeScheduler: ReminderSnoozeScheduler
@Inject lateinit var notifier: TaskNotifier
@Inject lateinit var settingsPrefs: SettingsPrefs
@Inject lateinit var startupGate: StartupGate
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
@@ -51,6 +57,13 @@ class BootReceiver : BroadcastReceiver() {
try {
runCatching { scheduler.sync(afterReboot = afterReboot) }
if (afterReboot) runCatching { snoozeScheduler.rearm() }
if (afterReboot) {
runCatching {
val settings = settingsPrefs.settings.first()
startupGate.awaitReady()
notifier.restorePersistent(settings)
}
}
} finally {
pending.finish()
}
@@ -115,6 +115,7 @@ internal fun reminderIsStale(occurrenceStart: Long?, current: Task?, missingMean
* Posts the reminder for [taskId]'s occurrence if it is still open, then checks
* once more: a completion landing between the read and the post may already
* have had its withdrawal pass, which ran before there was anything to withdraw.
* With [exact], a lookup that fell back to another occurrence posts nothing.
*/
internal fun TaskNotifier.postIfOpen(
dataSource: TasksDataSource,
@@ -122,10 +123,18 @@ internal fun TaskNotifier.postIfOpen(
occurrenceStart: Long,
settings: Settings,
alert: Boolean = true,
exact: Boolean = false,
postedAt: Long? = null,
) {
val task = dataSource.occurrence(taskId, occurrenceStart) ?: return
if (task.isClosed) return
postDue(task, settings, alert)
val task = dataSource.occurrence(taskId, occurrenceStart)
if (task == null || task.isClosed || (exact && !task.isOccurrence(occurrenceStart))) {
forget(taskId)
return
}
postDue(task, settings, alert, postedAt)
val now = runCatching { dataSource.occurrence(taskId, occurrenceStart) }.getOrElse { return }
if (now == null || now.isClosed) cancel(taskId)
}
private fun Task.isOccurrence(occurrenceStart: Long): Boolean =
occurrenceStart == ScheduledReminder.NO_OCCURRENCE || this.occurrenceStart?.toEpochMilliseconds() == occurrenceStart
@@ -70,10 +70,22 @@ class ReminderActionReceiver : BroadcastReceiver() {
}
ACTION_DISMISSED -> runCatching {
val store = intent.getStringExtra(EXTRA_STORE)
val settings = settingsPrefs.settings.first()
if (!settings.remindersEnabled || !settings.persistentReminders) return@runCatching
startupGate.awaitReady()
notifier.postIfOpen(dataSource, taskId, occurrence, settings, alert = false)
if (!settings.remindersEnabled || !settings.persistentReminders || !notifier.isCurrentStore(store)) {
notifier.forget(taskId, store)
return@runCatching
}
notifier.postIfOpen(
dataSource,
taskId,
occurrence,
settings,
alert = false,
exact = true,
postedAt = intent.getLongExtra(EXTRA_POSTED_AT, 0L).takeIf { it > 0L },
)
}
}
} finally {
@@ -90,6 +102,8 @@ class ReminderActionReceiver : BroadcastReceiver() {
private const val EXTRA_TASK_ID = "de.jeanlucmakiola.agendula.extra.TASK_ID"
private const val EXTRA_OCCURRENCE = "de.jeanlucmakiola.agendula.extra.OCCURRENCE_START"
private const val EXTRA_STORE = "de.jeanlucmakiola.agendula.extra.STORE"
private const val EXTRA_POSTED_AT = "de.jeanlucmakiola.agendula.extra.POSTED_AT"
/**
* The data URI is what keeps two reminders' PendingIntents apart —
@@ -101,5 +115,11 @@ class ReminderActionReceiver : BroadcastReceiver() {
.setData("agendula://reminder-action/$taskId/$occurrenceStart".toUri())
.putExtra(EXTRA_TASK_ID, taskId)
.putExtra(EXTRA_OCCURRENCE, occurrenceStart)
/** A persistent reminder's delete intent, naming the store its task id belongs to and when it was first shown. */
fun dismissedIntent(context: Context, taskId: Long, occurrenceStart: Long, store: String, postedAt: Long): Intent =
intent(context, ACTION_DISMISSED, taskId, occurrenceStart)
.putExtra(EXTRA_STORE, store)
.putExtra(EXTRA_POSTED_AT, postedAt)
}
}
@@ -21,7 +21,6 @@ import de.jeanlucmakiola.agendula.MainActivity
import de.jeanlucmakiola.agendula.R
import de.jeanlucmakiola.agendula.data.prefs.ReminderDescription
import de.jeanlucmakiola.agendula.data.prefs.Settings
import de.jeanlucmakiola.agendula.data.prefs.SettingsPrefs
import de.jeanlucmakiola.agendula.domain.readableDescription
import de.jeanlucmakiola.agendula.data.prefs.is24Hour
import de.jeanlucmakiola.agendula.data.di.ApplicationScope
@@ -32,7 +31,6 @@ import de.jeanlucmakiola.agendula.domain.Task
import de.jeanlucmakiola.agendula.domain.calendarDate
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import java.text.BreakIterator
import java.time.Instant as JInstant
@@ -50,8 +48,8 @@ import kotlin.time.Instant
* Posts one notification per due task on its list's channel, so each list can
* have its own sound and importance. The tag is the task id, so a re-fired alarm
* replaces rather than duplicates. Tapping opens the task's detail screen (see
* [MainActivity.taskIntent]). With [Settings.persistentReminders] a reminder is
* ongoing and re-posts silently when swiped away.
* [MainActivity.taskIntent]). With [Settings.persistentReminders] a reminder
* re-posts silently when swiped away and is remembered so a reboot brings it back.
*/
@Singleton
class TaskNotifier @Inject constructor(
@@ -59,11 +57,12 @@ class TaskNotifier @Inject constructor(
private val resolver: ProviderResolver,
private val dataSource: TasksDataSource,
private val startupGate: StartupGate,
private val settingsPrefs: SettingsPrefs,
@ApplicationScope private val scope: CoroutineScope,
) {
private val manager get() = context.getSystemService(NotificationManager::class.java)
private val channelPrefs get() = context.getSharedPreferences(CHANNEL_PREFS, Context.MODE_PRIVATE)
private val persistentPrefs get() = context.getSharedPreferences(PERSISTENT_PREFS, Context.MODE_PRIVATE)
private val currentStore get() = resolver.mode().name.lowercase()
fun canPost(): Boolean {
val granted = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
@@ -74,8 +73,11 @@ class TaskNotifier @Inject constructor(
// canPost() checks POST_NOTIFICATIONS before we ever call notify().
@SuppressLint("MissingPermission")
fun postDue(task: Task, settings: Settings, alert: Boolean = true) {
fun postDue(task: Task, settings: Settings, alert: Boolean = true, postedAt: Long? = null) {
if (!canPost()) return
val persistent = settings.persistentReminders
val occurrence = task.occurrenceStart?.toEpochMilliseconds() ?: ScheduledReminder.NO_OCCURRENCE
val shownAt = postedAt ?: System.currentTimeMillis()
val channelId = ensureListChannel(task.listId, task.listName)
val title = task.title.ifBlank { context.getString(R.string.task_untitled) }
val text = task.due?.let { due ->
@@ -111,20 +113,14 @@ class TaskNotifier @Inject constructor(
}
.setCategory(NotificationCompat.CATEGORY_REMINDER)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(!settings.persistentReminders)
.setOngoing(settings.persistentReminders)
.setWhen(shownAt)
.setAutoCancel(!persistent)
.setSilent(!alert)
// A group of its own, so a silent re-post doesn't land in NotificationCompat's shared "silent" group.
.apply { if (persistent) setGroup("$PERSISTENT_GROUP_PREFIX${task.taskId}") }
.setDeleteIntent(if (persistent) dismissedIntent(task.taskId, occurrence, shownAt) else null)
.setContentIntent(tapIntent)
.apply {
if (settings.persistentReminders) {
setDeleteIntent(actionIntent(task, ReminderActionReceiver.ACTION_DISMISSED))
}
}
.addExtras(
Bundle().apply {
putLong(EXTRA_OCCURRENCE, task.occurrenceStart?.toEpochMilliseconds() ?: ScheduledReminder.NO_OCCURRENCE)
},
)
.addExtras(Bundle().apply { putLong(EXTRA_OCCURRENCE, occurrence) })
.addAction(0, context.getString(R.string.reminder_action_done), actionIntent(task, ReminderActionReceiver.ACTION_DONE))
.addAction(
0,
@@ -133,6 +129,11 @@ class TaskNotifier @Inject constructor(
)
.build()
NotificationManagerCompat.from(context).notify(task.taskId.toString(), NOTIFICATION_ID, notification)
if (persistent) {
persistentPrefs.edit { putString(persistentKey(currentStore, task.taskId), encodePersistent(occurrence, shownAt)) }
} else {
forget(task.taskId)
}
}
/** Characters per line of an expanded notification on this screen, at the user's font size. */
@@ -147,45 +148,93 @@ class TaskNotifier @Inject constructor(
fun cancel(taskId: Long) {
NotificationManagerCompat.from(context).cancel(taskId.toString(), NOTIFICATION_ID)
forget(taskId)
}
/** Drops [taskId] from the persistent reminders remembered for [store], the current one by default. */
fun forget(taskId: Long, store: String? = null) {
persistentPrefs.edit { remove(persistentKey(store ?: currentStore, taskId)) }
}
fun isCurrentStore(store: String?): Boolean = store == currentStore
/**
* Takes down every posted reminder [isStale] says is done with — completed,
* cancelled or deleted since it went off, here or on another device. The
* occurrence is null for a reminder posted before it was recorded.
*/
fun withdrawStale(isStale: (taskId: Long, occurrenceStart: Long?) -> Boolean) {
postedReminders().forEach { (taskId, occurrence) -> if (isStale(taskId, occurrence)) cancel(taskId) }
postedReminders().forEach { if (isStale(it.taskId, it.occurrence)) cancel(it.taskId) }
}
/** Re-posts every shown reminder without alerting, so a change to [Settings.persistentReminders] reaches it. */
fun repostActive() {
fun repostActive(settings: Settings) {
scope.launch {
runCatching {
val settings = settingsPrefs.settings.first()
if (!settings.remindersEnabled) return@runCatching
startupGate.awaitReady()
postedReminders().forEach { (taskId, occurrence) ->
postedReminders().forEach { posted ->
runCatching {
postIfOpen(dataSource, taskId, occurrence ?: ScheduledReminder.NO_OCCURRENCE, settings, alert = false)
postIfOpen(
dataSource,
posted.taskId,
posted.occurrence ?: ScheduledReminder.NO_OCCURRENCE,
settings,
alert = false,
exact = true,
postedAt = posted.postedAt,
)
}
}
}
}
}
/** The current store's posted reminders as task id and occurrence; another store's ids name other tasks. */
private fun postedReminders(): List<Pair<Long, Long?>> {
val prefix = "$LIST_CHANNEL_PREFIX${resolver.mode().name.lowercase()}_"
/**
* Brings back the persistent reminders a reboot took down, silently and at
* their old time. Another store's are dropped: their ids name other tasks here.
*/
fun restorePersistent(settings: Settings) {
val remembered = persistentPrefs.all.mapNotNull { (key, value) ->
decodePersistentKey(key)?.let { (store, taskId) -> Triple(store, taskId, decodePersistent(value as? String)) }
}
if (!settings.remindersEnabled || !settings.persistentReminders) {
persistentPrefs.edit { clear() }
return
}
remembered.forEach { (store, taskId, shown) ->
if (store != currentStore || shown == null) {
forget(taskId, store)
return@forEach
}
runCatching {
postIfOpen(dataSource, taskId, shown.first, settings, alert = false, exact = true, postedAt = shown.second)
}
}
}
private class Posted(val taskId: Long, val occurrence: Long?, val postedAt: Long)
/** The current store's posted reminders; another store's ids name other tasks. */
private fun postedReminders(): List<Posted> {
val prefix = "$LIST_CHANNEL_PREFIX${currentStore}_"
return manager.activeNotifications
.filter { it.id == NOTIFICATION_ID && it.notification.channelId?.startsWith(prefix) == true }
.mapNotNull { posted ->
val taskId = posted.tag?.toLongOrNull() ?: return@mapNotNull null
val extras = posted.notification.extras
taskId to (if (extras.containsKey(EXTRA_OCCURRENCE)) extras.getLong(EXTRA_OCCURRENCE) else null)
val occurrence = if (extras.containsKey(EXTRA_OCCURRENCE)) extras.getLong(EXTRA_OCCURRENCE) else null
Posted(taskId, occurrence, posted.notification.`when`)
}
}
private fun dismissedIntent(taskId: Long, occurrence: Long, postedAt: Long): PendingIntent =
PendingIntent.getBroadcast(
context,
taskId.toInt(),
ReminderActionReceiver.dismissedIntent(context, taskId, occurrence, currentStore, postedAt),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
private fun actionIntent(task: Task, action: String): PendingIntent = PendingIntent.getBroadcast(
context,
task.taskId.toInt(),
@@ -262,6 +311,8 @@ class TaskNotifier @Inject constructor(
private const val EXTRA_OCCURRENCE = "de.jeanlucmakiola.agendula.extra.OCCURRENCE_START"
private const val CHANNEL_PREFS = "reminder_channels"
private const val KEY_LEGACY_IMPORTANCE = "legacy_importance"
private const val PERSISTENT_PREFS = "persistent_reminders"
private const val PERSISTENT_GROUP_PREFIX = "reminder_"
/**
* Whether a reminder can sound anywhere: the group is not blocked and at
@@ -275,6 +326,24 @@ class TaskNotifier @Inject constructor(
}
}
internal fun persistentKey(store: String, taskId: Long): String = "$store|$taskId"
internal fun decodePersistentKey(key: String): Pair<String, Long>? {
val store = key.substringBefore('|', "").ifEmpty { return null }
val taskId = key.substringAfter('|').toLongOrNull() ?: return null
return store to taskId
}
internal fun encodePersistent(occurrence: Long, postedAt: Long): String = "$occurrence|$postedAt"
/** A remembered persistent reminder as its occurrence and the time it was first shown. */
internal fun decodePersistent(value: String?): Pair<Long, Long>? {
val parts = value?.split('|')?.takeIf { it.size == 2 } ?: return null
val occurrence = parts[0].toLongOrNull() ?: return null
val postedAt = parts[1].toLongOrNull() ?: return null
return occurrence to postedAt
}
/** The words a reminder uses for the days either side of today. */
internal class RelativeDays(val today: String, val tomorrow: String, val yesterday: String)
@@ -58,6 +58,7 @@ import de.jeanlucmakiola.agendula.ui.common.formatMinuteOfDay
import de.jeanlucmakiola.agendula.ui.common.reminderLabel
import de.jeanlucmakiola.floret.components.CollapsingScaffold
import de.jeanlucmakiola.floret.components.GroupedRow
import de.jeanlucmakiola.floret.components.GroupedSwitchRow
import de.jeanlucmakiola.floret.components.OptionPicker
import de.jeanlucmakiola.floret.components.Position
import de.jeanlucmakiola.floret.components.SelectedCheck
@@ -209,14 +210,12 @@ internal fun NotificationsScreen(
trailing = if (batteryExempt) ({ SelectedCheck() }) else null,
onClick = { context.openBatteryOptimizationSettings() },
)
GroupedRow(
GroupedSwitchRow(
title = stringResource(R.string.settings_persistent_reminders),
summary = stringResource(R.string.settings_persistent_reminders_hint),
checked = state.settings.persistentReminders,
onCheckedChange = viewModel::setPersistentReminders,
position = Position.Middle,
trailing = {
Switch(checked = state.settings.persistentReminders, onCheckedChange = viewModel::setPersistentReminders)
},
onClick = { viewModel.setPersistentReminders(!state.settings.persistentReminders) },
)
GroupedRow(
title = stringResource(R.string.settings_snooze_duration),
@@ -33,6 +33,7 @@ import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
@@ -263,7 +264,7 @@ class SettingsViewModel @Inject constructor(
fun setReminderDescription(pref: ReminderDescription) = viewModelScope.launch { prefs.setReminderDescription(pref) }
fun setPersistentReminders(enabled: Boolean) = viewModelScope.launch {
prefs.setPersistentReminders(enabled)
taskNotifier.repostActive()
taskNotifier.repostActive(prefs.settings.first())
}
fun setShowAddSubtaskRow(show: Boolean) = viewModelScope.launch { prefs.setShowAddSubtaskRow(show) }
fun setBottomAddBar(enabled: Boolean) = viewModelScope.launch { prefs.setBottomAddBar(enabled) }
@@ -0,0 +1,33 @@
package de.jeanlucmakiola.agendula.data.reminders
import com.google.common.truth.Truth.assertThat
import org.junit.jupiter.api.Test
class PersistentRecordTest {
@Test
fun `key round-trips store and task id`() {
assertThat(decodePersistentKey(persistentKey("own", 42L))).isEqualTo("own" to 42L)
}
@Test
fun `malformed keys decode to null`() {
assertThat(decodePersistentKey("42")).isNull()
assertThat(decodePersistentKey("|42")).isNull()
assertThat(decodePersistentKey("own|x")).isNull()
}
@Test
fun `value round-trips occurrence and post time`() {
val value = encodePersistent(ScheduledReminder.NO_OCCURRENCE, 1_700_000_000_000L)
assertThat(decodePersistent(value)).isEqualTo(ScheduledReminder.NO_OCCURRENCE to 1_700_000_000_000L)
}
@Test
fun `malformed values decode to null`() {
assertThat(decodePersistent(null)).isNull()
assertThat(decodePersistent("12")).isNull()
assertThat(decodePersistent("12|x")).isNull()
assertThat(decodePersistent("1|2|3")).isNull()
}
}