From c52c6c54cc613eec64abeb97f55ed25dedba0023 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 17:00:46 +0100 Subject: [PATCH 01/11] feat(#171): full-screen reminder alerts per calendar --- app/build.gradle.kts | 1 + app/src/main/AndroidManifest.xml | 34 +++- .../calendula/data/prefs/SettingsPrefs.kt | 12 ++ .../data/reminders/FullScreenAlerts.kt | 33 ++++ .../data/reminders/ReminderActionReceiver.kt | 31 +-- .../data/reminders/ReminderChannelPlan.kt | 3 + .../data/reminders/ReminderChannels.kt | 37 +++- .../data/reminders/ReminderNotifier.kt | 127 ++++++++++-- .../data/reminders/ReminderRingService.kt | 160 ++++++++++++++++ .../domain/reminders/ReminderAlertStyle.kt | 43 +++++ .../ui/reminders/ReminderAlertActivity.kt | 161 ++++++++++++++++ .../ui/reminders/ReminderAlertScreen.kt | 180 ++++++++++++++++++ .../ui/reminders/ReminderAlertUiState.kt | 16 ++ .../ui/settings/NotificationSettings.kt | 117 +++++++++++- .../calendula/ui/settings/SettingsUiState.kt | 3 + .../ui/settings/SettingsViewModel.kt | 4 + app/src/main/res/values/strings.xml | 14 ++ .../calendula/data/prefs/SettingsPrefsTest.kt | 13 ++ .../reminders/ReminderAlertStyleTest.kt | 38 ++++ docs/ARCHITECTURE.md | 18 ++ docs/PRIVACY.md | 4 +- floret-kit | 2 +- 22 files changed, 1005 insertions(+), 46 deletions(-) create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyle.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt create mode 100644 app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertUiState.kt create mode 100644 app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyleTest.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 409adcb7..27bece29 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -182,6 +182,7 @@ dependencies { implementation("de.jeanlucmakiola.floret:identity") implementation("de.jeanlucmakiola.floret:components") implementation("de.jeanlucmakiola.floret:glance") + implementation("de.jeanlucmakiola.floret:ring") implementation(libs.kotlinx.coroutines.core) debugImplementation(libs.androidx.ui.tooling) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index b272d8e9..268f5624 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -41,10 +41,20 @@ --> - + - - + + + + + + + + + + + + > = prefs.flow(SettingsKeys.perCalendarEventDuration) val remindersEnabled: Flow = prefs.flow(SettingsKeys.remindersEnabled) val mutedReminderCalendarIds: Flow> = prefs.flow(SettingsKeys.mutedReminderCalendarIds) + val reminderAlertStyles: Flow> = prefs.flow(SettingsKeys.reminderAlertStyles) val allowColorOnUnsupportedCalendars: Flow = prefs.flow(SettingsKeys.allowColorOnUnsupportedCalendars) val defaultReminderMinutes: Flow> = prefs.flow(SettingsKeys.defaultReminderMinutes) @@ -278,6 +282,10 @@ class SettingsPrefs @Inject constructor( prefs.update(SettingsKeys.mutedReminderCalendarIds) { if (enabled) it - calendarId else it + calendarId } } + suspend fun setCalendarAlertStyle(calendarId: Long, style: ReminderAlertStyle) { + prefs.update(SettingsKeys.reminderAlertStyles) { it + (calendarId to style) } + } + suspend fun setAllowColorOnUnsupportedCalendars(enabled: Boolean) = prefs.set(SettingsKeys.allowColorOnUnsupportedCalendars, enabled) @@ -605,6 +613,10 @@ object SettingsKeys { */ val mutedReminderCalendarIds: Pref> = idSetPref("muted_reminder_calendar_ids") + /** Per-calendar alert styles (#171); a calendar absent from the map uses plain notifications. */ + val reminderAlertStyles: Pref> = + nullableStringPref("reminder_alert_styles").map(::parseAlertStyles) { it.toStoredAlertStyles() } + /** * Whether to offer a custom event colour on calendars that publish no colour * palette; synced ones without a palette (some CalDAV) may drop or overwrite diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt new file mode 100644 index 00000000..1ae01fa0 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt @@ -0,0 +1,33 @@ +package de.jeanlucmakiola.calendula.data.reminders + +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.SharedFlow +import kotlinx.coroutines.flow.asSharedFlow +import javax.inject.Inject +import javax.inject.Singleton + +/** + * What the full-screen alerts (#171) share within the process: the reminder + * [ReminderRingService] is ringing for, and the reminders just dismissed or + * snoozed, so an alert screen showing one closes whichever way it was handled. + */ +@Singleton +class FullScreenAlerts @Inject constructor() { + + /** Set by [ReminderRingService] for as long as it rings. */ + @Volatile + var ringing: ReminderAlert? = null + + private val handledKeys = MutableSharedFlow( + extraBufferCapacity = 8, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) + + /** The [ReminderAlert.key]s of reminders as they are dismissed or snoozed. */ + val handled: SharedFlow = handledKeys.asSharedFlow() + + fun markHandled(alert: ReminderAlert) { + handledKeys.tryEmit(alert.key) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderActionReceiver.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderActionReceiver.kt index c0bd7569..7329fd06 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderActionReceiver.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderActionReceiver.kt @@ -13,8 +13,8 @@ import javax.inject.Inject /** * Handles the "Snooze" and "Dismiss" actions on a reminder notification, plus * the internal re-show when a snooze elapses. All three are app-internal - * intents (notification action buttons and our own [ReminderSnoozeScheduler] - * alarm), so the receiver is not exported. + * intents (notification action buttons, the full-screen alert's buttons and + * our own [ReminderSnoozeScheduler] alarm), so the receiver is not exported. * * - **Dismiss** just cancels the notification — the scan's watermark has moved * past this reminder, so nothing re-posts it. @@ -74,6 +74,9 @@ class ReminderActionReceiver : BroadcastReceiver() { */ const val ACTION_OPEN = "de.jeanlucmakiola.calendula.reminders.OPEN" + /** Not handled here either: the slot of the full-screen alert's own intent (#171). */ + const val ACTION_ALERT_SCREEN = "de.jeanlucmakiola.calendula.reminders.ALERT_SCREEN" + private const val EXTRA_ALERT_KEY = "alert_key" private const val EXTRA_EVENT_ID = "event_id" private const val EXTRA_CALENDAR_ID = "calendar_id" @@ -94,16 +97,21 @@ class ReminderActionReceiver : BroadcastReceiver() { Intent(context, ReminderActionReceiver::class.java).apply { this.action = action data = "calendula://reminder/${identity(alert, action)}".toUri() - putExtra(EXTRA_ALERT_KEY, alert.key) - putExtra(EXTRA_EVENT_ID, alert.eventId) - putExtra(EXTRA_CALENDAR_ID, alert.calendarId) - putExtra(EXTRA_BEGIN, alert.beginMillis) - putExtra(EXTRA_END, alert.endMillis) - putExtra(EXTRA_TITLE, alert.title) - putExtra(EXTRA_LOCATION, alert.location) - putExtra(EXTRA_ALL_DAY, alert.isAllDay) + putAlert(alert) } + /** Carries [alert] as extras, for [alertFrom] to read back. */ + fun Intent.putAlert(alert: ReminderAlert): Intent = apply { + putExtra(EXTRA_ALERT_KEY, alert.key) + putExtra(EXTRA_EVENT_ID, alert.eventId) + putExtra(EXTRA_CALENDAR_ID, alert.calendarId) + putExtra(EXTRA_BEGIN, alert.beginMillis) + putExtra(EXTRA_END, alert.endMillis) + putExtra(EXTRA_TITLE, alert.title) + putExtra(EXTRA_LOCATION, alert.location) + putExtra(EXTRA_ALL_DAY, alert.isAllDay) + } + /** * A stable request code per (alert, action), so one notification's * PendingIntents stay distinct. The shift keeps the action slot intact; @@ -115,6 +123,7 @@ class ReminderActionReceiver : BroadcastReceiver() { ACTION_DISMISS -> 2 ACTION_SHOW -> 3 ACTION_OPEN -> 4 + ACTION_ALERT_SCREEN -> 5 else -> 0 } return (identity(alert, action).toInt() shl 3) + actionOffset @@ -123,7 +132,7 @@ class ReminderActionReceiver : BroadcastReceiver() { private fun identity(alert: ReminderAlert, action: String): Long = if (action == ACTION_SHOW) alert.occurrenceKey else alert.key - private fun alertFrom(intent: Intent): ReminderAlert? { + fun alertFrom(intent: Intent): ReminderAlert? { if (!intent.hasExtra(EXTRA_ALERT_KEY)) return null return ReminderAlert( key = intent.getLongExtra(EXTRA_ALERT_KEY, 0L), diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt index 1f070222..da13a7cf 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannelPlan.kt @@ -6,6 +6,9 @@ import de.jeanlucmakiola.calendula.ui.common.groupByAccount /** The single channel every reminder posted on before they moved per calendar (#145). */ const val LEGACY_REMINDER_CHANNEL_ID = "reminders" +/** The silent channel ringing full-screen alerts post on (#171); outside the per-calendar namespace. */ +const val RING_CHANNEL_ID = "reminders_ring" + private const val CHANNEL_PREFIX = "reminders.calendar." private const val GROUP_PREFIX = "reminders.account." private const val LOCAL_GROUP_ID = GROUP_PREFIX + "local" diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt index 2f80a55c..87894f57 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.data.reminders +import android.app.Notification import android.app.NotificationChannel import android.app.NotificationChannelGroup import android.app.NotificationManager @@ -9,6 +10,7 @@ import dagger.hilt.android.qualifiers.ApplicationContext import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle import de.jeanlucmakiola.calendula.ui.common.sourceAppLabel import java.util.Locale import javax.inject.Inject @@ -72,10 +74,41 @@ class ReminderChannels @Inject constructor( * has not got to it yet. Null when the calendar no longer exists. Should the * calendar lookup fail or come back empty, the channel is still created, * plainly named and ungrouped, for the next sync to name and file — a - * reminder is never lost to its channel. + * reminder is never lost to its channel. A ringing [style] posts on the + * shared ring channel instead, once the calendar is known to exist. */ @Synchronized - fun channelFor(calendarId: Long): String? { + fun channelFor(calendarId: Long, style: ReminderAlertStyle = ReminderAlertStyle.Notification): String? { + val calendarChannel = calendarChannelFor(calendarId) ?: return null + return if (style == ReminderAlertStyle.FullScreenRing) ringChannel() else calendarChannel + } + + /** + * The channel a ringing full-screen alert (#171) posts on, shared by every + * calendar. Silent: the ring service owns the sound and vibration, so the + * channel adds neither. High importance keeps the heads-up a denied + * full-screen intent degrades to. + */ + private fun ringChannel(): String { + val manager = manager + if (manager.getNotificationChannel(RING_CHANNEL_ID) == null) { + manager.createNotificationChannel( + NotificationChannel( + RING_CHANNEL_ID, + context.getString(R.string.reminder_ring_channel_name), + NotificationManager.IMPORTANCE_HIGH, + ).apply { + description = context.getString(R.string.reminder_ring_channel_description) + setSound(null, null) + enableVibration(false) + lockscreenVisibility = Notification.VISIBILITY_PUBLIC + }, + ) + } + return RING_CHANNEL_ID + } + + private fun calendarChannelFor(calendarId: Long): String? { val id = reminderChannelId(calendarId) val manager = manager if (manager.getNotificationChannel(id) != null) return id diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index 3631482e..d5b1dcb3 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt @@ -1,6 +1,7 @@ package de.jeanlucmakiola.calendula.data.reminders import android.Manifest +import android.app.Notification import android.app.PendingIntent import android.content.Context import android.os.Build @@ -16,7 +17,11 @@ import de.jeanlucmakiola.calendula.data.prefs.CalendarPrefs import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs import de.jeanlucmakiola.calendula.data.prefs.is24Hour import de.jeanlucmakiola.calendula.data.prefs.resolveFirstDay +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle +import de.jeanlucmakiola.calendula.domain.reminders.alertStyleFor +import de.jeanlucmakiola.calendula.ui.reminders.ReminderAlertActivity import de.jeanlucmakiola.floret.android.hasPermission +import de.jeanlucmakiola.floret.ring.canUseFullScreenIntent import kotlinx.coroutines.flow.first import kotlinx.datetime.isoDayNumber import java.time.DayOfWeek @@ -28,7 +33,8 @@ import javax.inject.Singleton /** * Posts one notification per occurrence on its calendar's channel - * ([ReminderChannels], #145). Tapping opens the event's detail screen. + * ([ReminderChannels], #145), or as a full-screen alert where the calendar + * asks for one (#171). Tapping opens the event's detail screen. * * The tag is the [occurrenceKey], so each reminder for an occurrence replaces * the one before it in place (#463). A different reminder alerts afresh; the @@ -42,6 +48,7 @@ class ReminderNotifier @Inject constructor( private val calendarPrefs: CalendarPrefs, private val calendarDataSource: CalendarDataSource, private val channels: ReminderChannels, + private val alerts: FullScreenAlerts, ) { /** False when the user declined `POST_NOTIFICATIONS` or muted the app. */ @@ -62,16 +69,54 @@ class ReminderNotifier @Inject constructor( calendarId in calendarPrefs.pendingDisabledCalendarIds.first() || calendarDataSource.isCalendarVisible(calendarId) == false - /** Post [alert], unless its calendar is silenced or gone. */ - suspend fun post(alert: ReminderAlert) { + /** + * Post [alert] in its calendar's alert style (#171), unless the calendar is + * silenced or gone. [quiet] posts it as a plain notification that makes no + * sound: a ring handing it back to the shade. + */ + suspend fun post(alert: ReminderAlert, quiet: Boolean = false) { if (isSilenced(alert.calendarId)) return - val channelId = try { - channels.channelFor(alert.calendarId) - } catch (e: Exception) { - Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e) - null - } ?: return + val style = if (quiet) { + ReminderAlertStyle.Notification + } else { + settingsPrefs.reminderAlertStyles.first().alertStyleFor(alert.calendarId) + } + val channelId = channelFor(alert, style) ?: return val title = displayTitle(alert) + val text = contentText(alert) + if (style == ReminderAlertStyle.FullScreenRing) { + val ringing = build(alert, channelId, title, text, fullScreen = true, ringing = true, quiet = false) + if (ReminderRingService.start(context, alert, ringing)) { + // An earlier reminder for this occurrence gives way to the ring. + NotificationManagerCompat.from(context).cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID) + cancelLegacy(alert) + return + } + // Android refused the ring: still full-screen, sounding once on the calendar's channel. + val fallback = channelFor(alert, ReminderAlertStyle.FullScreen) ?: return + notify(alert, build(alert, fallback, title, text, fullScreen = true, ringing = false, quiet = false)) + return + } + // A ring for this occurrence from before its calendar's style changed. + if (alerts.ringing?.occurrenceKey == alert.occurrenceKey) ReminderRingService.stop(context) + notify( + alert, + build(alert, channelId, title, text, fullScreen = style.isFullScreen, ringing = false, quiet = quiet), + ) + } + + private fun channelFor(alert: ReminderAlert, style: ReminderAlertStyle): String? = try { + channels.channelFor(alert.calendarId, style) + } catch (e: Exception) { + Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e) + null + } + + private suspend fun contentText(alert: ReminderAlert): String = + listOfNotNull(timeText(alert), alert.location).joinToString(" · ") + + /** When [alert]'s occurrence happens, as its notification words it. */ + suspend fun timeText(alert: ReminderAlert): String { val is24Hour = settingsPrefs.timeFormat.first() .is24Hour(android.text.format.DateFormat.is24HourFormat(context)) val zone = ZoneId.systemDefault() @@ -79,7 +124,7 @@ class ReminderNotifier @Inject constructor( // resolveFirstDay yields a kotlinx.datetime day; bridge it to java.time by // its shared ISO number (1..7) for the date math in reminderTimeText. val firstDayOfWeek = DayOfWeek.of(settingsPrefs.weekStart.first().resolveFirstDay(locale).isoDayNumber) - val time = reminderTimeText( + return reminderTimeText( beginMillis = alert.beginMillis, endMillis = alert.endMillis, isAllDay = alert.isAllDay, @@ -92,19 +137,34 @@ class ReminderNotifier @Inject constructor( tomorrowLabel = context.getString(R.string.reminder_day_tomorrow), yesterdayLabel = context.getString(R.string.reminder_day_yesterday), ) - val text = listOfNotNull(time, alert.location).joinToString(" · ") - val notification = NotificationCompat.Builder(context, channelId) + } + + /** + * The reminder's notification. A [ringing] one belongs to [ReminderRingService]: + * ongoing, opening the alert screen, and dismissed by a swipe, since from + * Android 14 a swipe can take it away while the ring goes on. [fullScreen] + * adds the alert screen as a full-screen intent where Android allows it, + * and degrades to a heads-up where it does not. + */ + private fun build( + alert: ReminderAlert, + channelId: String, + title: String, + text: String, + fullScreen: Boolean, + ringing: Boolean, + quiet: Boolean, + ): Notification { + val builder = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(text) .setWhen(alert.beginMillis) .setShowWhen(false) - .setCategory(NotificationCompat.CATEGORY_EVENT) - .setPriority(NotificationCompat.PRIORITY_HIGH) - .setAutoCancel(true) - .setOnlyAlertOnce(shownKey(alert) == alert.key) + .setCategory(if (ringing) NotificationCompat.CATEGORY_ALARM else NotificationCompat.CATEGORY_EVENT) + .setPriority(if (ringing) NotificationCompat.PRIORITY_MAX else NotificationCompat.PRIORITY_HIGH) .addExtras(Bundle().apply { putLong(EXTRA_REMINDER_KEY, alert.key) }) - .setContentIntent(detailIntent(alert)) + .setContentIntent(if (ringing) alertScreenIntent(alert) else detailIntent(alert)) .addAction( R.drawable.ic_notification_snooze, context.getString(R.string.reminder_action_snooze), @@ -115,7 +175,19 @@ class ReminderNotifier @Inject constructor( context.getString(R.string.reminder_action_dismiss), actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS), ) - .build() + if (ringing) { + builder.setOngoing(true) + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + .setDeleteIntent(actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS)) + } else { + builder.setAutoCancel(true).setOnlyAlertOnce(shownKey(alert) == alert.key) + } + if (quiet) builder.setSilent(true) + if (fullScreen && context.canUseFullScreenIntent()) builder.setFullScreenIntent(alertScreenIntent(alert), true) + return builder.build() + } + + private fun notify(alert: ReminderAlert, notification: Notification) { val manager = NotificationManagerCompat.from(context) cancelLegacy(alert) try { @@ -136,10 +208,20 @@ class ReminderNotifier @Inject constructor( if (shownKey(alert) == alert.key) manager.cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID) // Posted before reminders shared a notification, under the reminder's own key. manager.cancel(alert.key.toString(), NOTIFICATION_ID) + if (alerts.ringing?.key == alert.key) ReminderRingService.stop(context) + alerts.markHandled(alert) } /** Whether a different reminder for [alert]'s occurrence is on screen now. */ - fun isSuperseded(alert: ReminderAlert): Boolean = shownKey(alert).let { it != null && it != alert.key } + fun isSuperseded(alert: ReminderAlert): Boolean { + val ringing = alerts.ringing?.takeIf { it.occurrenceKey == alert.occurrenceKey } + if (ringing != null) return ringing.key != alert.key + return shownKey(alert).let { it != null && it != alert.key } + } + + /** Whether [alert] itself is still on screen, as a notification or ringing. */ + fun isShowing(alert: ReminderAlert): Boolean = + alerts.ringing?.key == alert.key || shownKey(alert) == alert.key /** The key of the reminder showing for [alert]'s occurrence, if any. */ private fun shownKey(alert: ReminderAlert): Long? { @@ -176,6 +258,13 @@ class ReminderNotifier @Inject constructor( PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) + private fun alertScreenIntent(alert: ReminderAlert): PendingIntent = PendingIntent.getActivity( + context, + ReminderActionReceiver.requestCode(alert, ReminderActionReceiver.ACTION_ALERT_SCREEN), + ReminderAlertActivity.intent(context, alert), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + private fun detailIntent(alert: ReminderAlert): PendingIntent = PendingIntent.getActivity( context, // Shares the per-(alert, action) request-code scheme with the buttons. diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt new file mode 100644 index 00000000..97e59fa9 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt @@ -0,0 +1,160 @@ +package de.jeanlucmakiola.calendula.data.reminders + +import android.app.Notification +import android.app.Service +import android.content.Context +import android.content.Intent +import android.media.RingtoneManager +import android.os.IBinder +import android.util.Log +import androidx.core.content.IntentCompat +import dagger.hilt.android.AndroidEntryPoint +import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver.Companion.putAlert +import de.jeanlucmakiola.floret.ring.RingVibrator +import de.jeanlucmakiola.floret.ring.RingWakeLock +import de.jeanlucmakiola.floret.ring.TonePlayer +import de.jeanlucmakiola.floret.ring.startRingForeground +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import javax.inject.Inject + +/** + * Rings a reminder whose calendar asks for "Ring until dismissed" (#171): the + * alarm sound looped with vibration, for as long as the reminder is neither + * dismissed nor snoozed, up to [RING_TIMEOUT_MILLIS]. Then it goes quiet and + * hands the reminder back to the shade as an ordinary notification. + * + * One reminder rings at a time. A new one takes over, and the one it replaces + * stays in the shade, silently, unless it was for the same occurrence. + */ +@AndroidEntryPoint +class ReminderRingService : Service() { + + @Inject lateinit var alerts: FullScreenAlerts + @Inject lateinit var notifier: ReminderNotifier + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + + private val tones by lazy { TonePlayer(this) } + private val vibrator by lazy { RingVibrator(this) } + private val wakeLock by lazy { RingWakeLock(this, WAKE_LOCK_TAG, RING_TIMEOUT_MILLIS) } + + private var ringing: Job? = null + private var timeout: Job? = null + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + val alert = intent?.let(ReminderActionReceiver::alertFrom) + val notification = intent?.let { IntentCompat.getParcelableExtra(it, EXTRA_NOTIFICATION, Notification::class.java) } + if (alert == null || notification == null) { + if (alerts.ringing == null) stopSelf() + return START_NOT_STICKY + } + // Before anything else: the platform gives a foreground service a few + // seconds to post its notification. + startRingForeground(RING_NOTIFICATION_ID, notification) + val previous = alerts.ringing + if (previous?.key == alert.key && timeout?.isActive == true) return START_REDELIVER_INTENT + alerts.ringing = alert + if (previous != null && previous.occurrenceKey != alert.occurrenceKey) { + scope.launch { notifier.post(previous, quiet = true) } + } + ring() + // Re-delivered rather than dropped, so a ring the system killed comes back. + return START_REDELIVER_INTENT + } + + override fun onDestroy() { + releaseRing() + alerts.ringing = null + scope.cancel() + super.onDestroy() + } + + private fun ring() { + releaseRing() + wakeLock.acquire() + // Vibration first: the sound may take a moment to open. + vibrator.start() + ringing = scope.launch { tones.play(scope, ringSources()) } + timeout = scope.launch { + delay(RING_TIMEOUT_MILLIS) + giveUp() + } + } + + /** Rung long enough: back to the shade quietly, so the reminder is not lost. */ + private suspend fun giveUp() { + timeout = null + val alert = alerts.ringing + releaseRing() + alerts.ringing = null + if (alert != null) { + try { + notifier.post(alert, quiet = true) + } catch (e: Exception) { + Log.w(TAG, "Could not hand the reminder of event ${alert.eventId} back", e) + } + } + stopForeground(STOP_FOREGROUND_REMOVE) + stopSelf() + } + + private fun releaseRing() { + ringing?.cancel() + ringing = null + timeout?.cancel() + timeout = null + tones.stop() + vibrator.stop() + wakeLock.release() + } + + /** The device's alarm sound, then the built-in ones; none opening leaves the vibration. */ + private fun ringSources() = listOfNotNull( + RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM), + RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM), + RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), + ) + + companion object { + private const val TAG = "ReminderRingService" + private const val EXTRA_NOTIFICATION = "notification" + private const val WAKE_LOCK_TAG = "calendula:reminder-ring" + + /** Distinct from the reminders' own id, which is shared under per-occurrence tags. */ + private const val RING_NOTIFICATION_ID = 2 + + /** How long a reminder rings unanswered before it goes quiet. */ + const val RING_TIMEOUT_MILLIS = 10L * 60 * 1000 + + /** + * Rings [alert] under [notification]. False when Android refused to + * start the service from where the reminder fired. + */ + fun start(context: Context, alert: ReminderAlert, notification: Notification): Boolean { + val intent = Intent(context, ReminderRingService::class.java) + .putAlert(alert) + .putExtra(EXTRA_NOTIFICATION, notification) + return try { + RingWakeLock.handOff(context, WAKE_LOCK_TAG) + context.startForegroundService(intent) + true + } catch (e: Exception) { + Log.w(TAG, "Could not start the ring for event ${alert.eventId}", e) + false + } + } + + /** `stopService`, not a command: a command is a start, which can throw from the background. */ + fun stop(context: Context) { + context.stopService(Intent(context, ReminderRingService::class.java)) + } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyle.kt b/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyle.kt new file mode 100644 index 00000000..850efaad --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyle.kt @@ -0,0 +1,43 @@ +package de.jeanlucmakiola.calendula.domain.reminders + +/** How a calendar's reminders get the user's attention (#171). */ +enum class ReminderAlertStyle(val storageValue: String) { + /** An ordinary notification on the calendar's channel. */ + Notification("notification"), + + /** A full-screen alert that sounds the calendar's notification sound once and stays until handled. */ + FullScreen("full_screen"), + + /** A full-screen alert that rings and vibrates like an alarm until handled. */ + FullScreenRing("full_screen_ring"), + ; + + val isFullScreen: Boolean get() = this != Notification + + companion object { + fun fromStorage(value: String): ReminderAlertStyle? = entries.firstOrNull { it.storageValue == value } + } +} + +/** [calendarId]'s alert style; a calendar without one uses plain notifications. */ +fun Map.alertStyleFor(calendarId: Long): ReminderAlertStyle = + this[calendarId] ?: ReminderAlertStyle.Notification + +/** + * Parse `id=style` entries joined by `;`. Malformed entries and unknown styles + * are dropped, so a garbled value degrades to plain notifications. + */ +fun parseAlertStyles(stored: String?): Map = + stored?.split(";").orEmpty().mapNotNull { entry -> + val parts = entry.split("=") + if (parts.size != 2) return@mapNotNull null + val calendarId = parts[0].trim().toLongOrNull() ?: return@mapNotNull null + val style = ReminderAlertStyle.fromStorage(parts[1].trim()) ?: return@mapNotNull null + calendarId to style + }.toMap() + +/** The stored form of [parseAlertStyles]; plain-notification entries are left out. */ +fun Map.toStoredAlertStyles(): String = + entries.filter { it.value != ReminderAlertStyle.Notification } + .sortedBy { it.key } + .joinToString(";") { (id, style) -> "$id=${style.storageValue}" } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt new file mode 100644 index 00000000..ce74b5e1 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt @@ -0,0 +1,161 @@ +package de.jeanlucmakiola.calendula.ui.reminders + +import android.content.Context +import android.content.Intent +import android.os.Bundle +import android.util.Log +import androidx.activity.ComponentActivity +import androidx.activity.compose.BackHandler +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.lifecycleScope +import androidx.lifecycle.repeatOnLifecycle +import dagger.hilt.android.AndroidEntryPoint +import de.jeanlucmakiola.calendula.data.calendar.CalendarDataSource +import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs +import de.jeanlucmakiola.calendula.data.reminders.FullScreenAlerts +import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver +import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver.Companion.putAlert +import de.jeanlucmakiola.calendula.data.reminders.ReminderAlert +import de.jeanlucmakiola.calendula.data.reminders.ReminderNotifier +import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors +import de.jeanlucmakiola.calendula.ui.theme.CalendulaTheme +import de.jeanlucmakiola.calendula.ui.theme.WindowThemeCache +import de.jeanlucmakiola.floret.di.IoDispatcher +import de.jeanlucmakiola.floret.prefs.ThemeMode +import de.jeanlucmakiola.floret.prefs.isDark +import de.jeanlucmakiola.floret.prefs.isPureBlack +import de.jeanlucmakiola.floret.ring.showOverLockScreen +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import javax.inject.Inject + +/** + * The full-screen reminder alert (#171), opened by the reminder's full-screen + * intent over the lock screen, or from its heads-up while the phone is in use. + * It stays until the reminder is dismissed or snoozed — here, from the + * notification, or by the ring giving up — and back does not close it. + */ +@AndroidEntryPoint +class ReminderAlertActivity : ComponentActivity() { + + @Inject lateinit var notifier: ReminderNotifier + @Inject lateinit var alerts: FullScreenAlerts + @Inject lateinit var settingsPrefs: SettingsPrefs + @Inject lateinit var calendarDataSource: CalendarDataSource + + @Inject @IoDispatcher + lateinit var io: CoroutineDispatcher + + private var state by mutableStateOf(ReminderAlertUiState.Loading) + private var alert: ReminderAlert? = null + private var loading: Job? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + showOverLockScreen() + enableEdgeToEdge() + show(intent) + lifecycleScope.launch { + repeatOnLifecycle(Lifecycle.State.CREATED) { + alerts.handled.collect { key -> if (key == alert?.key) finish() } + } + } + val cachedTheme = WindowThemeCache.read(this) ?: ThemeMode.SYSTEM + val cachedDynamicColor = WindowThemeCache.readDynamicColor(this) ?: true + setContent { + val themeMode by settingsPrefs.themeMode.collectAsStateWithLifecycle(cachedTheme) + val dynamicColor by settingsPrefs.dynamicColor.collectAsStateWithLifecycle(cachedDynamicColor) + val soften by settingsPrefs.softenCalendarColors.collectAsStateWithLifecycle(true) + CalendulaTheme( + darkTheme = themeMode.isDark(isSystemInDarkTheme()), + dynamicColor = dynamicColor, + pureBlack = themeMode.isPureBlack, + ) { + CompositionLocalProvider(LocalSoftenColors provides soften) { + BackHandler(enabled = true) { /* Handled by Dismiss or Snooze, not by leaving. */ } + when (val current = state) { + ReminderAlertUiState.Loading -> + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surface) {} + is ReminderAlertUiState.Showing -> ReminderAlertScreen( + state = current, + onSnooze = { act(ReminderActionReceiver.ACTION_SNOOZE) }, + onDismiss = { act(ReminderActionReceiver.ACTION_DISMISS) }, + ) + } + } + } + } + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + show(intent) + } + + /** Tapped from a stale notification, or handled while this window was away. */ + override fun onResume() { + super.onResume() + val current = alert + if (current != null && !notifier.isShowing(current)) finish() + } + + private fun show(intent: Intent) { + val next = ReminderActionReceiver.alertFrom(intent) + if (next == null) { + finish() + return + } + alert = next + loading?.cancel() + state = ReminderAlertUiState.Loading + loading = lifecycleScope.launch { + val calendar = try { + withContext(io) { calendarDataSource.calendars().firstOrNull { it.id == next.calendarId } } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + // The alert still shows, only without its calendar. + Log.w(TAG, "Could not read the calendar of event ${next.eventId}", e) + null + } + state = ReminderAlertUiState.Showing( + title = next.title, + time = notifier.timeText(next), + location = next.location?.takeIf { it.isNotBlank() }, + calendarName = calendar?.displayName, + calendarColor = calendar?.color, + ) + } + } + + private fun act(action: String) { + val current = alert ?: return + sendBroadcast(ReminderActionReceiver.intent(this, action, current)) + finish() + } + + companion object { + private const val TAG = "ReminderAlertActivity" + + fun intent(context: Context, alert: ReminderAlert): Intent = + Intent(context, ReminderAlertActivity::class.java) + .putAlert(alert) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_USER_ACTION) + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt new file mode 100644 index 00000000..ea972e6d --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt @@ -0,0 +1,180 @@ +package de.jeanlucmakiola.calendula.ui.reminders + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Event +import androidx.compose.material.icons.outlined.LocationOn +import androidx.compose.material.icons.outlined.Snooze +import androidx.compose.material.icons.rounded.Close +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import de.jeanlucmakiola.calendula.R +import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors +import de.jeanlucmakiola.calendula.ui.common.eventFill +import de.jeanlucmakiola.calendula.ui.common.eventInk +import de.jeanlucmakiola.floret.identity.LocalFloretDarkTheme +import de.jeanlucmakiola.floret.ring.RingBadge + +/** + * The alert itself, after the incoming-call screen: the calendar's pulsing + * badge, what and when in the middle, and the two ways out at the bottom, + * large enough to hit half awake. + */ +@Composable +internal fun ReminderAlertScreen( + state: ReminderAlertUiState.Showing, + onSnooze: () -> Unit, + onDismiss: () -> Unit, + modifier: Modifier = Modifier, +) { + Surface(modifier.fillMaxSize(), color = MaterialTheme.colorScheme.surfaceContainer) { + Column( + modifier = Modifier + .fillMaxSize() + .safeDrawingPadding() + .padding(horizontal = 24.dp, vertical = 32.dp), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + state.calendarName?.let { + Text( + text = it, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + Spacer(Modifier.weight(1f)) + CalendarBadge(state.calendarColor) + Spacer(Modifier.size(32.dp)) + Text( + text = state.title.ifBlank { stringResource(R.string.event_untitled) }, + style = MaterialTheme.typography.displaySmall, + color = MaterialTheme.colorScheme.onSurface, + textAlign = TextAlign.Center, + maxLines = 3, + overflow = TextOverflow.Ellipsis, + ) + Spacer(Modifier.size(12.dp)) + Text( + text = state.time, + style = MaterialTheme.typography.titleLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + state.location?.let { location -> + Spacer(Modifier.size(8.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = Icons.Outlined.LocationOn, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp), + ) + Spacer(Modifier.size(4.dp)) + Text( + text = location, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } + Spacer(Modifier.weight(1.5f)) + Row( + modifier = Modifier.fillMaxWidth().widthIn(max = 480.dp), + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + AlertButton( + label = stringResource(R.string.reminder_action_snooze), + icon = Icons.Outlined.Snooze, + tonal = true, + onClick = onSnooze, + modifier = Modifier.weight(1f), + ) + AlertButton( + label = stringResource(R.string.reminder_action_dismiss), + icon = Icons.Rounded.Close, + tonal = false, + onClick = onDismiss, + modifier = Modifier.weight(1f), + ) + } + } + } +} + +/** The calendar's colour as the badge fill, or the theme's primary container without one. */ +@Composable +private fun CalendarBadge(color: Int?) { + if (color == null) { + RingBadge(icon = Icons.Outlined.Event, size = 120.dp) + return + } + val fill = eventFill(color, LocalFloretDarkTheme.current, LocalSoftenColors.current) + RingBadge( + icon = Icons.Outlined.Event, + containerColor = fill, + contentColor = eventInk(fill, alpha = 1f), + size = 120.dp, + ) +} + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +private fun AlertButton( + label: String, + icon: ImageVector, + tonal: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val height = ButtonDefaults.LargeContainerHeight + val content: @Composable () -> Unit = { + Icon(icon, contentDescription = null, modifier = Modifier.size(ButtonDefaults.iconSizeFor(height))) + Spacer(Modifier.size(ButtonDefaults.iconSpacingFor(height))) + Text(label, style = ButtonDefaults.textStyleFor(height), maxLines = 1, overflow = TextOverflow.Ellipsis) + } + val buttonModifier = modifier.heightIn(min = height) + val padding = ButtonDefaults.contentPaddingFor(height) + if (tonal) { + FilledTonalButton( + onClick = onClick, + modifier = buttonModifier, + shapes = ButtonDefaults.shapesFor(height), + contentPadding = padding, + ) { content() } + } else { + Button( + onClick = onClick, + modifier = buttonModifier, + shapes = ButtonDefaults.shapesFor(height), + contentPadding = padding, + ) { content() } + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertUiState.kt new file mode 100644 index 00000000..8368a571 --- /dev/null +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertUiState.kt @@ -0,0 +1,16 @@ +package de.jeanlucmakiola.calendula.ui.reminders + +sealed interface ReminderAlertUiState { + /** The calendar is still being read; the surface is already up. */ + data object Loading : ReminderAlertUiState + + data class Showing( + /** Raw title; blank shows as "(no title)". */ + val title: String, + val time: String, + val location: String?, + /** Null when the calendar could not be read. */ + val calendarName: String?, + val calendarColor: Int?, + ) : ReminderAlertUiState +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt index b87b4b9c..48b387c0 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt @@ -34,6 +34,8 @@ import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle +import de.jeanlucmakiola.calendula.domain.reminders.alertStyleFor import de.jeanlucmakiola.calendula.ui.common.CalendarColorChip import de.jeanlucmakiola.calendula.ui.common.DurationPicker import de.jeanlucmakiola.calendula.ui.common.REMINDER_PRESETS @@ -47,11 +49,14 @@ import de.jeanlucmakiola.floret.components.CollapsingScaffold import de.jeanlucmakiola.floret.components.ExpandIcon 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 import de.jeanlucmakiola.floret.identity.collapseExit import de.jeanlucmakiola.floret.identity.expandEnter import de.jeanlucmakiola.floret.reminders.ReminderOverride +import de.jeanlucmakiola.floret.ring.canUseFullScreenIntent +import de.jeanlucmakiola.floret.ring.openFullScreenIntentSettings import de.jeanlucmakiola.floret.reminders.minutesOrEmpty import de.jeanlucmakiola.floret.reminders.reminderOverrideFor import kotlinx.coroutines.launch @@ -89,6 +94,9 @@ internal fun NotificationsScreen( var showAllDayReminderTime by remember { mutableStateOf(false) } var showSnooze by remember { mutableStateOf(false) } var overrideDialog by remember { mutableStateOf(null) } + var alertStylePicker by remember { mutableStateOf(null) } + var alertSoundPicker by remember { mutableStateOf(null) } + val canFullScreen = rememberCanUseFullScreenIntent() var calendarSectionExpanded by remember { mutableStateOf(false) } var expandedCalendars by remember { mutableStateOf(emptySet()) } val scope = rememberCoroutineScope() @@ -217,6 +225,10 @@ internal fun NotificationsScreen( notifying = notifying, onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) }, onOpenSound = { openCalendarSound(calendar.id) }, + canFullScreen = canFullScreen, + onEditAlertStyle = { alertStylePicker = calendar.id }, + onEditAlertSound = { alertSoundPicker = calendar.id }, + onAllowFullScreen = { context.openFullScreenIntentSettings() }, onOpenSpecialDates = onOpenSpecialDates, onEditOverride = { overrideDialog = it }, ) @@ -227,6 +239,51 @@ internal fun NotificationsScreen( } } + alertStylePicker?.let { calendarId -> + val current = state.reminderAlertStyles.alertStyleFor(calendarId) + OptionPicker( + title = stringResource(R.string.settings_alert_style), + options = listOf(ReminderAlertStyle.Notification, ReminderAlertStyle.FullScreen), + selected = if (current.isFullScreen) ReminderAlertStyle.FullScreen else ReminderAlertStyle.Notification, + label = { alertStyleLabel(it) }, + summary = { + stringResource( + if (it.isFullScreen) { + R.string.settings_alert_style_full_screen_summary + } else { + R.string.settings_alert_style_notification_summary + }, + ) + }, + onSelect = { picked -> + if (picked.isFullScreen != current.isFullScreen) { + viewModel.setCalendarAlertStyle(calendarId, picked) + // Guide the user straight to the switch Android 14+ may hold back. + if (picked.isFullScreen && !canFullScreen) context.openFullScreenIntentSettings() + } + }, + onDismiss = { alertStylePicker = null }, + ) + } + alertSoundPicker?.let { calendarId -> + OptionPicker( + title = stringResource(R.string.settings_alert_sound), + options = listOf(ReminderAlertStyle.FullScreen, ReminderAlertStyle.FullScreenRing), + selected = state.reminderAlertStyles.alertStyleFor(calendarId), + label = { alertSoundLabel(it) }, + summary = { + stringResource( + if (it == ReminderAlertStyle.FullScreenRing) { + R.string.settings_alert_sound_ring_summary + } else { + R.string.settings_alert_sound_once_summary + }, + ) + }, + onSelect = { viewModel.setCalendarAlertStyle(calendarId, it) }, + onDismiss = { alertSoundPicker = null }, + ) + } if (showSnooze) { DurationPicker( title = stringResource(R.string.settings_snooze_duration), @@ -318,11 +375,17 @@ private fun CalendarNotificationRows( notifying: Boolean, onSetNotifying: (Boolean) -> Unit, onOpenSound: () -> Unit, + canFullScreen: Boolean, + onEditAlertStyle: () -> Unit, + onEditAlertSound: () -> Unit, + onAllowFullScreen: () -> Unit, onOpenSpecialDates: () -> Unit, onEditOverride: (OverrideTarget) -> Unit, ) { val managed = calendar.id in state.managedCalendarIds val takesOverrides = calendar.canModifyContents && !managed + val alertStyle = state.reminderAlertStyles.alertStyleFor(calendar.id) + val needsPermission = alertStyle.isFullScreen && !canFullScreen Column { GroupedSwitchRow( title = stringResource(R.string.settings_calendar_notifications), @@ -334,10 +397,34 @@ private fun CalendarNotificationRows( GroupedRow( title = stringResource(R.string.settings_notification_sound), summary = stringResource(R.string.settings_calendar_notification_sound_hint), - position = if (managed || takesOverrides) Position.Middle else Position.Bottom, + position = Position.Middle, trailing = { ExternalLinkIcon() }, onClick = onOpenSound, ) + val lastAlertRow = !(managed || takesOverrides) + GroupedRow( + title = stringResource(R.string.settings_alert_style), + summary = alertStyleLabel(alertStyle), + position = if (lastAlertRow && !alertStyle.isFullScreen) Position.Bottom else Position.Middle, + onClick = onEditAlertStyle, + ) + if (alertStyle.isFullScreen) { + GroupedRow( + title = stringResource(R.string.settings_alert_sound), + summary = alertSoundLabel(alertStyle), + position = if (lastAlertRow && !needsPermission) Position.Bottom else Position.Middle, + onClick = onEditAlertSound, + ) + } + if (needsPermission) { + GroupedRow( + title = stringResource(R.string.settings_full_screen_permission), + summary = stringResource(R.string.settings_full_screen_permission_hint), + position = if (lastAlertRow) Position.Bottom else Position.Middle, + trailing = { ExternalLinkIcon() }, + onClick = onAllowFullScreen, + ) + } if (managed) { GroupedRow( title = stringResource(R.string.settings_default_reminder_allday), @@ -399,6 +486,20 @@ private fun calendarOverrideSummary( is ReminderOverride.Minutes -> reminderChoiceLabel(choice.minutes) } +@Composable +private fun alertStyleLabel(style: ReminderAlertStyle): String = stringResource( + if (style.isFullScreen) R.string.settings_alert_style_full_screen else R.string.settings_alert_style_notification, +) + +@Composable +private fun alertSoundLabel(style: ReminderAlertStyle): String = stringResource( + if (style == ReminderAlertStyle.FullScreenRing) R.string.settings_alert_sound_ring else R.string.settings_alert_sound_once, +) + +/** Whether Android lets full-screen alerts open, re-read on every `ON_RESUME` like [rememberBatteryOptimizationExempt]. */ +@Composable +private fun rememberCanUseFullScreenIntent(): Boolean = rememberOnResume { it.canUseFullScreenIntent() } + /** Snooze delays offered for the notification "Snooze" action, in minutes. */ private val SNOOZE_PRESETS = listOf(5, 10, 15, 30, 60) @@ -407,20 +508,22 @@ private val SNOOZE_PRESETS = listOf(5, 10, 15, 30, 60) * `ON_RESUME` so a change made in system settings shows up at once. */ @Composable -private fun rememberBatteryOptimizationExempt(): Boolean { +private fun rememberBatteryOptimizationExempt(): Boolean = rememberOnResume(::isIgnoringBatteryOptimizations) + +/** [read], re-read on every `ON_RESUME` so a change made in system settings shows up at once. */ +@Composable +private fun rememberOnResume(read: (Context) -> Boolean): Boolean { val context = LocalContext.current - var exempt by remember { mutableStateOf(isIgnoringBatteryOptimizations(context)) } + var value by remember { mutableStateOf(read(context)) } val lifecycleOwner = LocalLifecycleOwner.current DisposableEffect(lifecycleOwner) { val observer = LifecycleEventObserver { _, event -> - if (event == Lifecycle.Event.ON_RESUME) { - exempt = isIgnoringBatteryOptimizations(context) - } + if (event == Lifecycle.Event.ON_RESUME) value = read(context) } lifecycleOwner.lifecycle.addObserver(observer) onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } } - return exempt + return value } private fun isIgnoringBatteryOptimizations(context: Context): Boolean { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt index 43a8edce..af27bcf5 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsUiState.kt @@ -1,5 +1,6 @@ package de.jeanlucmakiola.calendula.ui.settings +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle import de.jeanlucmakiola.floret.reminders.ReminderOverride import de.jeanlucmakiola.calendula.data.prefs.PastEventDisplay import de.jeanlucmakiola.calendula.data.prefs.SettingsPrefs @@ -102,6 +103,8 @@ data class SettingsUiState( val reminderCalendars: List = emptyList(), /** Calendars whose reminders Calendula doesn't post (#272). */ val mutedReminderCalendarIds: Set = emptySet(), + /** Per-calendar alert styles (#171); absent means a plain notification. */ + val reminderAlertStyles: Map = emptyMap(), /** * Whether the event-colour picker is offered on calendars that publish no * colour palette (the colour may then not survive their next sync). diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index 5dae73ee..278b6e45 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt @@ -37,6 +37,7 @@ import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref import de.jeanlucmakiola.calendula.data.reminders.ReminderChannels import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner import de.jeanlucmakiola.calendula.domain.CalendarSource +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle import de.jeanlucmakiola.calendula.domain.EventFormField import de.jeanlucmakiola.calendula.domain.FontRole import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType @@ -131,6 +132,7 @@ class SettingsViewModel @Inject constructor( writableCalendars = calendars.filter { it.canModifyContents }, reminderCalendars = calendars, mutedReminderCalendarIds = this[SettingsKeys.mutedReminderCalendarIds], + reminderAlertStyles = this[SettingsKeys.reminderAlertStyles], allowColorOnUnsupportedCalendars = this[SettingsKeys.allowColorOnUnsupportedCalendars], managedCalendarIds = specialDatesCalendars.values.toSet(), ) @@ -370,6 +372,8 @@ class SettingsViewModel @Inject constructor( } } + fun setCalendarAlertStyle(calendarId: Long, style: ReminderAlertStyle) = save { setCalendarAlertStyle(calendarId, style) } + /** [calendarId]'s reminder channel, created if needed so its system settings can open (#340). */ suspend fun reminderChannelFor(calendarId: Long): String? = onChannels { channelFor(calendarId) } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index cc92c56e..3e0ffec5 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -376,6 +376,8 @@ Not now Snooze Dismiss + Ringing reminders + Full-screen reminders that ring until you dismiss them. Calendula plays their sound itself. Today Tomorrow @@ -738,6 +740,18 @@ Notification sound Sound, vibration and pop-ups for each calendar, in system settings Sound, vibration and pop-ups for this calendar, in system settings + Alert style + Notification + A notification that pops up and waits in the shade + Full-screen alert + Fills the screen, even on the lock screen, until you dismiss or snooze it + Full-screen sound + Play sound once + This calendar\'s notification sound, once + Ring until dismissed + Your alarm sound and vibration, like an alarm + Allow full-screen alerts + Android blocks Calendula\'s full-screen alerts, so they only pop up as notifications. Tap to allow them. Default (%1$s) Reliable delivery Android may delay reminders to save battery. Exempt Calendula so they arrive on time. diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt index 1e113689..beb7a63e 100644 --- a/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt +++ b/app/src/test/java/de/jeanlucmakiola/calendula/data/prefs/SettingsPrefsTest.kt @@ -10,6 +10,7 @@ import com.google.common.truth.Truth.assertThat import de.jeanlucmakiola.calendula.domain.EventFormField import de.jeanlucmakiola.calendula.domain.FontRole import de.jeanlucmakiola.calendula.domain.contacts.SpecialDateType +import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle import de.jeanlucmakiola.calendula.ui.agenda.AgendaRange import de.jeanlucmakiola.calendula.ui.common.CalendarView import de.jeanlucmakiola.calendula.ui.common.IMPLEMENTED_VIEWS @@ -614,6 +615,18 @@ class SettingsPrefsTest { assertThat(prefs.mutedReminderCalendarIds.first()).containsExactly(9L) } + @Test + fun `calendar alert styles default to notifications and persist per calendar`( + @TempDir tempDir: Path, + ) = runTest { + val prefs = testSettings(tempDir) + assertThat(prefs.reminderAlertStyles.first()).isEmpty() + prefs.setCalendarAlertStyle(7L, ReminderAlertStyle.FullScreenRing) + prefs.setCalendarAlertStyle(9L, ReminderAlertStyle.FullScreen) + prefs.setCalendarAlertStyle(9L, ReminderAlertStyle.Notification) + assertThat(prefs.reminderAlertStyles.first()).containsExactly(7L, ReminderAlertStyle.FullScreenRing) + } + @Test fun `garbage per-calendar duration entries are dropped, the rest survive`( @TempDir tempDir: Path, diff --git a/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyleTest.kt b/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyleTest.kt new file mode 100644 index 00000000..17e9b0ec --- /dev/null +++ b/app/src/test/java/de/jeanlucmakiola/calendula/domain/reminders/ReminderAlertStyleTest.kt @@ -0,0 +1,38 @@ +package de.jeanlucmakiola.calendula.domain.reminders + +import com.google.common.truth.Truth.assertThat +import org.junit.jupiter.api.Test + +class ReminderAlertStyleTest { + + @Test + fun `styles round-trip through their stored form`() { + val styles = mapOf(9L to ReminderAlertStyle.FullScreenRing, 3L to ReminderAlertStyle.FullScreen) + + assertThat(parseAlertStyles(styles.toStoredAlertStyles())).isEqualTo(styles) + } + + @Test + fun `plain notifications are not stored`() { + val stored = mapOf(1L to ReminderAlertStyle.Notification, 2L to ReminderAlertStyle.FullScreen).toStoredAlertStyles() + + assertThat(stored).isEqualTo("2=full_screen") + } + + @Test + fun `garbled entries are dropped, the rest survive`() { + assertThat(parseAlertStyles("x=full_screen;4=loud;5;6=full_screen_ring")) + .containsExactly(6L, ReminderAlertStyle.FullScreenRing) + assertThat(parseAlertStyles(null)).isEmpty() + } + + @Test + fun `a calendar without a style uses notifications`() { + val styles = mapOf(1L to ReminderAlertStyle.FullScreen) + + assertThat(styles.alertStyleFor(1L)).isEqualTo(ReminderAlertStyle.FullScreen) + assertThat(styles.alertStyleFor(2L)).isEqualTo(ReminderAlertStyle.Notification) + assertThat(ReminderAlertStyle.Notification.isFullScreen).isFalse() + assertThat(ReminderAlertStyle.FullScreenRing.isFullScreen).isTrue() + } +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 4822bd47..861ec3dc 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -409,6 +409,24 @@ off switch (#272): the scan plans nothing for those calendars (so they arm no wake-ups; toggling it re-scans), and `ReminderNotifier.post` checks it again for snoozes. +**Full-screen alerts (#171).** Settings → Notifications gives each calendar an +alert style (`SettingsPrefs.reminderAlertStyles`): a plain notification, a +full-screen alert that sounds once, or one that rings until handled. Only +`ReminderNotifier.post` reads it, and `ReminderChannels.channelFor(id, style)` +picks the channel. "Sound once" stays on the calendar's own channel, so its +sound is still the one chosen in system settings, and adds a full-screen intent +to `ReminderAlertActivity`. "Ring" starts `ReminderRingService`, which goes +foreground on the shared silent `reminders_ring` channel and loops the alarm +sound with vibration through floret-kit's `ring` module — the same player +Clockula's alarms use. One reminder rings at a time; a newer one takes over and +hands the older back to the shade quietly, as does a ring left unanswered for +ten minutes. Dismiss and Snooze, from the screen, the notification or a swipe, +all go through `ReminderActionReceiver`, so the ring stops and the screen +closes (`FullScreenAlerts`) however the reminder was handled. When Android 14+ +withholds `USE_FULL_SCREEN_INTENT`, the intent is left off and the alert is a +heads-up; Settings shows a row leading to the system switch. When Android +refuses the ring service, the reminder falls back to sounding once. + Deliberately absent: a fallback to the provider's `EVENT_REMINDER` broadcast. Keeping both would double-post wherever the provider works, and Etar's way out — a latch that disables its own scheduling once a real broadcast arrives — cannot diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md index adfd8a34..ae5cda07 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -96,9 +96,7 @@ The settings screen contains links to the source code, the licence, the issue tr - `USE_EXACT_ALARM`, `SCHEDULE_EXACT_ALARM`: deliver reminders at the exact time, including after snoozing. - `RECEIVE_BOOT_COMPLETED`: re-register pending reminders after a restart. - `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS`: only to open the system dialog for the “Reliable delivery” setting. -- `WAKE_LOCK`, `FOREGROUND_SERVICE`, `ACCESS_NETWORK_STATE`: required by the Android system component used for scheduled background work (WorkManager). - -`ACCESS_NETWORK_STATE` allows reading *whether* a network connection exists. It does **not** permit using one. Without `INTERNET`, no connection is possible. +- `USE_FULL_SCREEN_INTENT`, `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_SYSTEM_EXEMPTED`, `WAKE_LOCK`, `VIBRATE`: only for calendars you set to full-screen alerts — showing the alert over the lock screen and, with “Ring until dismissed”, ringing and vibrating until you dismiss or snooze it. ## 7. Distribution channels diff --git a/floret-kit b/floret-kit index 730c9eb2..86b8e608 160000 --- a/floret-kit +++ b/floret-kit @@ -1 +1 @@ -Subproject commit 730c9eb25a6bf2f93e3388bf132769d6dd1afd91 +Subproject commit 86b8e608623d6e254d74c6ea7362e04cc26a9adf From 0b223f53fce8903593be1c6f921b13cfabca473f Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 17:12:03 +0100 Subject: [PATCH 02/11] fix(#171): review round 1 - ring ids, hand-back off the main thread, blocked channels, closing the alert screen --- app/src/main/AndroidManifest.xml | 17 ++--- .../data/reminders/FullScreenAlerts.kt | 4 ++ .../data/reminders/ReminderChannels.kt | 43 +++++++---- .../data/reminders/ReminderNotifier.kt | 41 ++++++++--- .../data/reminders/ReminderRingService.kt | 72 +++++++++++++++---- .../ui/reminders/ReminderAlertActivity.kt | 11 +++ .../ui/settings/SettingsViewModel.kt | 9 ++- docs/PRIVACY.md | 3 +- floret-kit | 2 +- 9 files changed, 147 insertions(+), 55 deletions(-) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 268f5624..ba46a26e 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -44,12 +44,7 @@ - + @@ -332,19 +327,15 @@ android:name=".data.reminders.ReminderActionReceiver" android:exported="false" /> - + + android:taskAffinity="" /> - + ( extraBufferCapacity = 8, onBufferOverflow = BufferOverflow.DROP_OLDEST, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt index 87894f57..87c13362 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -59,6 +59,7 @@ class ReminderChannels @Inject constructor( channels = plan.channelsToWrite, existing = existing, ) + if (RING_CHANNEL_ID in existingIds) writeRingChannel() val ids = existingIds - plan.staleChannelIds.toSet() + plan.channelsToWrite.map { it.id } lastSync = syncKey(calendars, if (retireLegacyChannel()) ids - LEGACY_REMINDER_CHANNEL_ID else ids) } @@ -91,23 +92,37 @@ class ReminderChannels @Inject constructor( */ private fun ringChannel(): String { val manager = manager - if (manager.getNotificationChannel(RING_CHANNEL_ID) == null) { - manager.createNotificationChannel( - NotificationChannel( - RING_CHANNEL_ID, - context.getString(R.string.reminder_ring_channel_name), - NotificationManager.IMPORTANCE_HIGH, - ).apply { - description = context.getString(R.string.reminder_ring_channel_description) - setSound(null, null) - enableVibration(false) - lockscreenVisibility = Notification.VISIBILITY_PUBLIC - }, - ) - } + if (manager.getNotificationChannel(RING_CHANNEL_ID) == null) writeRingChannel() return RING_CHANNEL_ID } + /** Creates the ring channel, or renames it after a language change. */ + private fun writeRingChannel() { + manager.createNotificationChannel( + NotificationChannel( + RING_CHANNEL_ID, + context.getString(R.string.reminder_ring_channel_name), + NotificationManager.IMPORTANCE_HIGH, + ).apply { + description = context.getString(R.string.reminder_ring_channel_description) + setSound(null, null) + enableVibration(false) + lockscreenVisibility = Notification.VISIBILITY_PUBLIC + }, + ) + } + + /** + * Whether a ring may sound for [calendarId]: neither its own channel nor + * the ring channel is blocked, since the service plays the sound itself. + */ + fun canRing(calendarId: Long): Boolean { + val manager = manager + return listOf(reminderChannelId(calendarId), RING_CHANNEL_ID).none { + manager.getNotificationChannel(it)?.importance == NotificationManager.IMPORTANCE_NONE + } + } + private fun calendarChannelFor(calendarId: Long): String? { val id = reminderChannelId(calendarId) val manager = manager diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index d5b1dcb3..30024e7a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt @@ -76,17 +76,23 @@ class ReminderNotifier @Inject constructor( */ suspend fun post(alert: ReminderAlert, quiet: Boolean = false) { if (isSilenced(alert.calendarId)) return - val style = if (quiet) { - ReminderAlertStyle.Notification - } else { - settingsPrefs.reminderAlertStyles.first().alertStyleFor(alert.calendarId) + val style = when { + quiet -> ReminderAlertStyle.Notification + else -> settingsPrefs.reminderAlertStyles.first().alertStyleFor(alert.calendarId).let { + // A calendar or ring channel the user blocked must not ring regardless. + if (it == ReminderAlertStyle.FullScreenRing && !channels.canRing(alert.calendarId)) { + ReminderAlertStyle.FullScreen + } else { + it + } + } } val channelId = channelFor(alert, style) ?: return val title = displayTitle(alert) val text = contentText(alert) if (style == ReminderAlertStyle.FullScreenRing) { val ringing = build(alert, channelId, title, text, fullScreen = true, ringing = true, quiet = false) - if (ReminderRingService.start(context, alert, ringing)) { + if (ReminderRingService.start(context, alerts, alert, ringing)) { // An earlier reminder for this occurrence gives way to the ring. NotificationManagerCompat.from(context).cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID) cancelLegacy(alert) @@ -98,7 +104,7 @@ class ReminderNotifier @Inject constructor( return } // A ring for this occurrence from before its calendar's style changed. - if (alerts.ringing?.occurrenceKey == alert.occurrenceKey) ReminderRingService.stop(context) + stopRing { it.occurrenceKey == alert.occurrenceKey } notify( alert, build(alert, channelId, title, text, fullScreen = style.isFullScreen, ringing = false, quiet = quiet), @@ -175,10 +181,10 @@ class ReminderNotifier @Inject constructor( context.getString(R.string.reminder_action_dismiss), actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS), ) + // A swipe dismisses a full-screen alert, so its screen closes too. + if (fullScreen) builder.setDeleteIntent(actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS)) if (ringing) { - builder.setOngoing(true) - .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) - .setDeleteIntent(actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS)) + builder.setOngoing(true).setVisibility(NotificationCompat.VISIBILITY_PUBLIC) } else { builder.setAutoCancel(true).setOnlyAlertOnce(shownKey(alert) == alert.key) } @@ -208,10 +214,25 @@ class ReminderNotifier @Inject constructor( if (shownKey(alert) == alert.key) manager.cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID) // Posted before reminders shared a notification, under the reminder's own key. manager.cancel(alert.key.toString(), NOTIFICATION_ID) - if (alerts.ringing?.key == alert.key) ReminderRingService.stop(context) + stopRing { it.key == alert.key } alerts.markHandled(alert) } + /** + * Stop the ring if it is for a reminder [matching]. While a newer ring is + * still on its way to the service, that one takes over instead, and the + * stopped reminder is not handed back to the shade. + */ + fun stopRing(matching: (ReminderAlert) -> Boolean) { + val ringing = alerts.ringing ?: return + if (!matching(ringing)) return + if (alerts.starting != null) { + alerts.ringing = null + } else { + ReminderRingService.stop(context) + } + } + /** Whether a different reminder for [alert]'s occurrence is on screen now. */ fun isSuperseded(alert: ReminderAlert): Boolean { val ringing = alerts.ringing?.takeIf { it.occurrenceKey == alert.occurrenceKey } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt index 97e59fa9..760140d2 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt @@ -7,6 +7,7 @@ import android.content.Intent import android.media.RingtoneManager import android.os.IBinder import android.util.Log +import androidx.core.app.NotificationManagerCompat import androidx.core.content.IntentCompat import dagger.hilt.android.AndroidEntryPoint import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver.Companion.putAlert @@ -14,6 +15,7 @@ import de.jeanlucmakiola.floret.ring.RingVibrator import de.jeanlucmakiola.floret.ring.RingWakeLock import de.jeanlucmakiola.floret.ring.TonePlayer import de.jeanlucmakiola.floret.ring.startRingForeground +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -21,6 +23,7 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import javax.inject.Inject /** @@ -46,33 +49,60 @@ class ReminderRingService : Service() { private var ringing: Job? = null private var timeout: Job? = null + private var notificationId = RING_NOTIFICATION_ID + private var lastStartId: Int? = null + + /** What this service rings, which [FullScreenAlerts.ringing] may already have let go of. */ + private var currentKey: Long? = null override fun onBind(intent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { val alert = intent?.let(ReminderActionReceiver::alertFrom) val notification = intent?.let { IntentCompat.getParcelableExtra(it, EXTRA_NOTIFICATION, Notification::class.java) } + if (alerts.starting == alert?.key) alerts.starting = null if (alert == null || notification == null) { if (alerts.ringing == null) stopSelf() return START_NOT_STICKY } - // Before anything else: the platform gives a foreground service a few - // seconds to post its notification. - startRingForeground(RING_NOTIFICATION_ID, notification) + // Null when the user handled it while this ring was on its way. val previous = alerts.ringing - if (previous?.key == alert.key && timeout?.isActive == true) return START_REDELIVER_INTENT + // A different reminder posts under the other id, so it is a new + // notification whose full-screen intent opens; an update would not. + val replacing = currentKey != null && currentKey != alert.key + val shown = notificationId + if (replacing) notificationId = if (shown == RING_NOTIFICATION_ID) OTHER_RING_NOTIFICATION_ID else RING_NOTIFICATION_ID + val foreground = runCatching { startRingForeground(notificationId, notification) } + if (foreground.isFailure) { + // A restart after a process death may be refused a foreground start: + // the reminder goes back to the shade rather than being lost. + Log.w(TAG, "Could not ring for event ${alert.eventId}", foreground.exceptionOrNull()) + notificationId = shown + scope.launch { + handBack(alert) + if (alerts.ringing == null) stopSelf() + } + return START_NOT_STICKY + } + if (replacing) NotificationManagerCompat.from(this).cancel(shown) + // Only the newest start is redelivered after a process death; the older + // ones are done, so a handled reminder never rings again. + lastStartId?.let { stopSelfResult(it) } + lastStartId = startId + if (currentKey == alert.key && timeout?.isActive == true) return START_REDELIVER_INTENT + currentKey = alert.key alerts.ringing = alert if (previous != null && previous.occurrenceKey != alert.occurrenceKey) { - scope.launch { notifier.post(previous, quiet = true) } + scope.launch { handBack(previous) } } ring() - // Re-delivered rather than dropped, so a ring the system killed comes back. return START_REDELIVER_INTENT } override fun onDestroy() { releaseRing() alerts.ringing = null + alerts.starting = null scope.cancel() super.onDestroy() } @@ -89,23 +119,32 @@ class ReminderRingService : Service() { } } - /** Rung long enough: back to the shade quietly, so the reminder is not lost. */ + /** Rung long enough: back to the shade quietly, and the alert screen closes. */ private suspend fun giveUp() { timeout = null + currentKey = null val alert = alerts.ringing releaseRing() alerts.ringing = null if (alert != null) { - try { - notifier.post(alert, quiet = true) - } catch (e: Exception) { - Log.w(TAG, "Could not hand the reminder of event ${alert.eventId} back", e) - } + handBack(alert) + alerts.markHandled(alert) } stopForeground(STOP_FOREGROUND_REMOVE) stopSelf() } + /** [alert] as a quiet notification in the shade, so it is not lost. */ + private suspend fun handBack(alert: ReminderAlert) { + try { + withContext(Dispatchers.IO) { notifier.post(alert, quiet = true) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Could not hand the reminder of event ${alert.eventId} back", e) + } + } + private fun releaseRing() { ringing?.cancel() ringing = null @@ -128,8 +167,9 @@ class ReminderRingService : Service() { private const val EXTRA_NOTIFICATION = "notification" private const val WAKE_LOCK_TAG = "calendula:reminder-ring" - /** Distinct from the reminders' own id, which is shared under per-occurrence tags. */ - private const val RING_NOTIFICATION_ID = 2 + /** Clear of the reminders' tagged id 1 and the backup notice's 2. */ + private const val RING_NOTIFICATION_ID = 171 + private const val OTHER_RING_NOTIFICATION_ID = 172 /** How long a reminder rings unanswered before it goes quiet. */ const val RING_TIMEOUT_MILLIS = 10L * 60 * 1000 @@ -138,16 +178,18 @@ class ReminderRingService : Service() { * Rings [alert] under [notification]. False when Android refused to * start the service from where the reminder fired. */ - fun start(context: Context, alert: ReminderAlert, notification: Notification): Boolean { + fun start(context: Context, alerts: FullScreenAlerts, alert: ReminderAlert, notification: Notification): Boolean { val intent = Intent(context, ReminderRingService::class.java) .putAlert(alert) .putExtra(EXTRA_NOTIFICATION, notification) return try { RingWakeLock.handOff(context, WAKE_LOCK_TAG) + alerts.starting = alert.key context.startForegroundService(intent) true } catch (e: Exception) { Log.w(TAG, "Could not start the ring for event ${alert.eventId}", e) + alerts.starting = null false } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt index ce74b5e1..a4adc810 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt @@ -4,6 +4,7 @@ import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log +import android.view.WindowManager import androidx.activity.ComponentActivity import androidx.activity.compose.BackHandler import androidx.activity.compose.setContent @@ -17,6 +18,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier +import androidx.core.net.toUri import androidx.lifecycle.Lifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.lifecycleScope @@ -29,6 +31,7 @@ import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver.Companion.putAlert import de.jeanlucmakiola.calendula.data.reminders.ReminderAlert import de.jeanlucmakiola.calendula.data.reminders.ReminderNotifier +import de.jeanlucmakiola.calendula.data.reminders.ReminderRingService import de.jeanlucmakiola.calendula.ui.common.LocalSoftenColors import de.jeanlucmakiola.calendula.ui.theme.CalendulaTheme import de.jeanlucmakiola.calendula.ui.theme.WindowThemeCache @@ -40,6 +43,7 @@ import de.jeanlucmakiola.floret.ring.showOverLockScreen import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Job +import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import javax.inject.Inject @@ -69,6 +73,11 @@ class ReminderAlertActivity : ComponentActivity() { super.onCreate(savedInstanceState) showOverLockScreen() enableEdgeToEdge() + lifecycleScope.launch { + // An alert nobody answers lets the display sleep again; it stays on the lock screen. + delay(SCREEN_ON_MILLIS) + window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } show(intent) lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.CREATED) { @@ -152,9 +161,11 @@ class ReminderAlertActivity : ComponentActivity() { companion object { private const val TAG = "ReminderAlertActivity" + private const val SCREEN_ON_MILLIS = ReminderRingService.RING_TIMEOUT_MILLIS fun intent(context: Context, alert: ReminderAlert): Intent = Intent(context, ReminderAlertActivity::class.java) + .setData("calendula://reminder-alert/${alert.key}".toUri()) .putAlert(alert) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_USER_ACTION) } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index 278b6e45..aa43614a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt @@ -35,6 +35,7 @@ import de.jeanlucmakiola.floret.prefs.ThemeMode import de.jeanlucmakiola.calendula.data.prefs.TimeFormatPref import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref import de.jeanlucmakiola.calendula.data.reminders.ReminderChannels +import de.jeanlucmakiola.calendula.data.reminders.ReminderNotifier import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle @@ -72,6 +73,7 @@ class SettingsViewModel @Inject constructor( private val launcherNameManager: LauncherNameManager, private val reminderScanner: ReminderScanner, private val reminderChannels: ReminderChannels, + private val reminderNotifier: ReminderNotifier, @IoDispatcher private val io: CoroutineDispatcher, @ApplicationContext private val appContext: Context, ) : ViewModel() { @@ -360,6 +362,7 @@ class SettingsViewModel @Inject constructor( fun setRemindersEnabled(enabled: Boolean) { viewModelScope.launch { prefs.setRemindersEnabled(enabled) + if (!enabled) reminderNotifier.stopRing { true } reminderScanner.scan() } } @@ -368,11 +371,15 @@ class SettingsViewModel @Inject constructor( fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) { viewModelScope.launch { prefs.setCalendarRemindersEnabled(calendarId, enabled) + if (!enabled) reminderNotifier.stopRing { it.calendarId == calendarId } reminderScanner.scan() } } - fun setCalendarAlertStyle(calendarId: Long, style: ReminderAlertStyle) = save { setCalendarAlertStyle(calendarId, style) } + fun setCalendarAlertStyle(calendarId: Long, style: ReminderAlertStyle) { + save { setCalendarAlertStyle(calendarId, style) } + if (style != ReminderAlertStyle.FullScreenRing) reminderNotifier.stopRing { it.calendarId == calendarId } + } /** [calendarId]'s reminder channel, created if needed so its system settings can open (#340). */ suspend fun reminderChannelFor(calendarId: Long): String? = onChannels { channelFor(calendarId) } diff --git a/docs/PRIVACY.md b/docs/PRIVACY.md index ae5cda07..e542cedb 100644 --- a/docs/PRIVACY.md +++ b/docs/PRIVACY.md @@ -96,7 +96,8 @@ The settings screen contains links to the source code, the licence, the issue tr - `USE_EXACT_ALARM`, `SCHEDULE_EXACT_ALARM`: deliver reminders at the exact time, including after snoozing. - `RECEIVE_BOOT_COMPLETED`: re-register pending reminders after a restart. - `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS`: only to open the system dialog for the “Reliable delivery” setting. -- `USE_FULL_SCREEN_INTENT`, `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_SYSTEM_EXEMPTED`, `WAKE_LOCK`, `VIBRATE`: only for calendars you set to full-screen alerts — showing the alert over the lock screen and, with “Ring until dismissed”, ringing and vibrating until you dismiss or snooze it. +- `USE_FULL_SCREEN_INTENT`, `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_SYSTEM_EXEMPTED`, `VIBRATE`: for calendars you set to full-screen alerts — showing the alert over the lock screen and, with “Ring until dismissed”, ringing and vibrating until you dismiss or snooze it. +- `WAKE_LOCK`: keeps the phone awake while a full-screen alert rings, and lets the Android component that runs scheduled background work (WorkManager) finish it. ## 7. Distribution channels diff --git a/floret-kit b/floret-kit index 86b8e608..e316e8f2 160000 --- a/floret-kit +++ b/floret-kit @@ -1 +1 @@ -Subproject commit 86b8e608623d6e254d74c6ea7362e04cc26a9adf +Subproject commit e316e8f2368e2f379c88bf0a8e35d3a1e7900731 From d2b6637f7232c0cb424539885e9a034ce9781533 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 17:20:13 +0100 Subject: [PATCH 03/11] chore(#171): floret-kit ring review fixes --- floret-kit | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/floret-kit b/floret-kit index e316e8f2..b1401bcf 160000 --- a/floret-kit +++ b/floret-kit @@ -1 +1 @@ -Subproject commit e316e8f2368e2f379c88bf0a8e35d3a1e7900731 +Subproject commit b1401bcf6a76f675bf1b53bb4da5b1be8971757e From 6cf6a6fdbff1d7933e791409570c0e0aff537aa8 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 17:33:26 +0100 Subject: [PATCH 04/11] fix(#171): review round 2 - ordered ring commands, hand-back that outlives the service, in-call and blocked-group checks, scrolling alert screen --- .../data/reminders/FullScreenAlerts.kt | 35 +++- .../data/reminders/ReminderChannels.kt | 11 +- .../data/reminders/ReminderNotifier.kt | 68 +++----- .../data/reminders/ReminderRingService.kt | 149 ++++++++++++------ .../ui/reminders/ReminderAlertActivity.kt | 22 ++- .../ui/reminders/ReminderAlertScreen.kt | 101 +++++++----- .../ui/settings/NotificationSettings.kt | 23 ++- .../ui/settings/SettingsViewModel.kt | 10 +- app/src/main/res/values/strings.xml | 3 +- docs/ARCHITECTURE.md | 10 +- floret-kit | 2 +- 11 files changed, 267 insertions(+), 167 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt index 5426465a..71947ae8 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt @@ -4,6 +4,7 @@ import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow +import java.util.concurrent.atomic.AtomicInteger import javax.inject.Inject import javax.inject.Singleton @@ -15,23 +16,47 @@ import javax.inject.Singleton @Singleton class FullScreenAlerts @Inject constructor() { - /** Set by [ReminderRingService] for as long as it rings. */ + /** Written only by [ReminderRingService], on the main thread, for as long as it rings. */ @Volatile var ringing: ReminderAlert? = null + internal set - /** The key of a ring handed to [ReminderRingService] that has not reached it yet. */ - @Volatile - var starting: Long? = null + /** Rings handed to [ReminderRingService] that have not reached it yet. */ + internal val pendingStarts = AtomicInteger(0) + + /** Whether a ring is going or on its way, so a stop is worth sending. */ + val mayBeRinging: Boolean get() = ringing != null || pendingStarts.get() > 0 private val handledKeys = MutableSharedFlow( extraBufferCapacity = 8, onBufferOverflow = BufferOverflow.DROP_OLDEST, ) - /** The [ReminderAlert.key]s of reminders as they are dismissed or snoozed. */ + /** The [ReminderAlert.key]s of reminders as they are dismissed, snoozed or handed back. */ val handled: SharedFlow = handledKeys.asSharedFlow() fun markHandled(alert: ReminderAlert) { handledKeys.tryEmit(alert.key) } } + +/** Which ring a stop is for. */ +sealed interface RingMatch { + fun matches(alert: ReminderAlert): Boolean + + data class Key(val key: Long) : RingMatch { + override fun matches(alert: ReminderAlert) = alert.key == key + } + + data class Occurrence(val occurrenceKey: Long) : RingMatch { + override fun matches(alert: ReminderAlert) = alert.occurrenceKey == occurrenceKey + } + + data class Calendar(val calendarId: Long) : RingMatch { + override fun matches(alert: ReminderAlert) = alert.calendarId == calendarId + } + + data object Any : RingMatch { + override fun matches(alert: ReminderAlert) = true + } +} diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt index 87c13362..c6686ed0 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -113,13 +113,16 @@ class ReminderChannels @Inject constructor( } /** - * Whether a ring may sound for [calendarId]: neither its own channel nor - * the ring channel is blocked, since the service plays the sound itself. + * Whether a ring may sound for [calendarId]: neither its own channel, its + * account's group nor the ring channel is blocked, since the service plays + * the sound itself. */ fun canRing(calendarId: Long): Boolean { val manager = manager - return listOf(reminderChannelId(calendarId), RING_CHANNEL_ID).none { - manager.getNotificationChannel(it)?.importance == NotificationManager.IMPORTANCE_NONE + return listOf(reminderChannelId(calendarId), RING_CHANNEL_ID).none { id -> + val channel = manager.getNotificationChannel(id) ?: return@none false + channel.importance == NotificationManager.IMPORTANCE_NONE || + channel.group?.let { manager.getNotificationChannelGroup(it)?.isBlocked } == true } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index 30024e7a..2e446bfc 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt @@ -71,28 +71,25 @@ class ReminderNotifier @Inject constructor( /** * Post [alert] in its calendar's alert style (#171), unless the calendar is - * silenced or gone. [quiet] posts it as a plain notification that makes no - * sound: a ring handing it back to the shade. + * silenced or gone. [ring] false posts a ringing style as a full-screen + * alert that sounds once instead; [quiet] posts a plain notification that + * makes no sound. Both are how a ring hands a reminder back to the shade. */ - suspend fun post(alert: ReminderAlert, quiet: Boolean = false) { + suspend fun post(alert: ReminderAlert, quiet: Boolean = false, ring: Boolean = true) { if (isSilenced(alert.calendarId)) return + val chosen = settingsPrefs.reminderAlertStyles.first().alertStyleFor(alert.calendarId) val style = when { quiet -> ReminderAlertStyle.Notification - else -> settingsPrefs.reminderAlertStyles.first().alertStyleFor(alert.calendarId).let { - // A calendar or ring channel the user blocked must not ring regardless. - if (it == ReminderAlertStyle.FullScreenRing && !channels.canRing(alert.calendarId)) { - ReminderAlertStyle.FullScreen - } else { - it - } - } + // A calendar or ring channel the user blocked must not ring regardless. + chosen == ReminderAlertStyle.FullScreenRing && (!ring || !channels.canRing(alert.calendarId)) -> + ReminderAlertStyle.FullScreen + else -> chosen } val channelId = channelFor(alert, style) ?: return val title = displayTitle(alert) val text = contentText(alert) if (style == ReminderAlertStyle.FullScreenRing) { - val ringing = build(alert, channelId, title, text, fullScreen = true, ringing = true, quiet = false) - if (ReminderRingService.start(context, alerts, alert, ringing)) { + if (ReminderRingService.start(context, alerts, alert, build(alert, channelId, title, text, style, quiet))) { // An earlier reminder for this occurrence gives way to the ring. NotificationManagerCompat.from(context).cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID) cancelLegacy(alert) @@ -100,15 +97,12 @@ class ReminderNotifier @Inject constructor( } // Android refused the ring: still full-screen, sounding once on the calendar's channel. val fallback = channelFor(alert, ReminderAlertStyle.FullScreen) ?: return - notify(alert, build(alert, fallback, title, text, fullScreen = true, ringing = false, quiet = false)) + notify(alert, build(alert, fallback, title, text, ReminderAlertStyle.FullScreen, quiet)) return } - // A ring for this occurrence from before its calendar's style changed. - stopRing { it.occurrenceKey == alert.occurrenceKey } - notify( - alert, - build(alert, channelId, title, text, fullScreen = style.isFullScreen, ringing = false, quiet = quiet), - ) + // A fresh reminder replaces a ring for its occurrence from before the style changed. + if (ring) stopRing(RingMatch.Occurrence(alert.occurrenceKey)) + notify(alert, build(alert, channelId, title, text, style, quiet)) } private fun channelFor(alert: ReminderAlert, style: ReminderAlertStyle): String? = try { @@ -146,21 +140,22 @@ class ReminderNotifier @Inject constructor( } /** - * The reminder's notification. A [ringing] one belongs to [ReminderRingService]: - * ongoing, opening the alert screen, and dismissed by a swipe, since from - * Android 14 a swipe can take it away while the ring goes on. [fullScreen] - * adds the alert screen as a full-screen intent where Android allows it, - * and degrades to a heads-up where it does not. + * The reminder's notification in [style]. A ringing one belongs to + * [ReminderRingService]: ongoing and opening the alert screen. A full-screen + * one adds the alert screen as a full-screen intent where Android allows + * it, degrading to a heads-up where it does not, and is dismissed by a + * swipe, so its screen closes too. */ private fun build( alert: ReminderAlert, channelId: String, title: String, text: String, - fullScreen: Boolean, - ringing: Boolean, + style: ReminderAlertStyle, quiet: Boolean, ): Notification { + val ringing = style == ReminderAlertStyle.FullScreenRing + val fullScreen = style.isFullScreen val builder = NotificationCompat.Builder(context, channelId) .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) @@ -181,7 +176,6 @@ class ReminderNotifier @Inject constructor( context.getString(R.string.reminder_action_dismiss), actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS), ) - // A swipe dismisses a full-screen alert, so its screen closes too. if (fullScreen) builder.setDeleteIntent(actionIntent(alert, ReminderActionReceiver.ACTION_DISMISS)) if (ringing) { builder.setOngoing(true).setVisibility(NotificationCompat.VISIBILITY_PUBLIC) @@ -214,23 +208,13 @@ class ReminderNotifier @Inject constructor( if (shownKey(alert) == alert.key) manager.cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID) // Posted before reminders shared a notification, under the reminder's own key. manager.cancel(alert.key.toString(), NOTIFICATION_ID) - stopRing { it.key == alert.key } + stopRing(RingMatch.Key(alert.key)) alerts.markHandled(alert) } - /** - * Stop the ring if it is for a reminder [matching]. While a newer ring is - * still on its way to the service, that one takes over instead, and the - * stopped reminder is not handed back to the shade. - */ - fun stopRing(matching: (ReminderAlert) -> Boolean) { - val ringing = alerts.ringing ?: return - if (!matching(ringing)) return - if (alerts.starting != null) { - alerts.ringing = null - } else { - ReminderRingService.stop(context) - } + /** Stop the ring if it is for a reminder [match]es; [handBack] keeps it in the shade, quietly. */ + fun stopRing(match: RingMatch, handBack: Boolean = false) { + if (alerts.mayBeRinging) ReminderRingService.stop(context, match, handBack) } /** Whether a different reminder for [alert]'s occurrence is on screen now. */ diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt index 760140d2..8a167daf 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt @@ -10,10 +10,12 @@ import android.util.Log import androidx.core.app.NotificationManagerCompat import androidx.core.content.IntentCompat import dagger.hilt.android.AndroidEntryPoint +import de.jeanlucmakiola.calendula.data.di.ApplicationScope import de.jeanlucmakiola.calendula.data.reminders.ReminderActionReceiver.Companion.putAlert import de.jeanlucmakiola.floret.ring.RingVibrator import de.jeanlucmakiola.floret.ring.RingWakeLock import de.jeanlucmakiola.floret.ring.TonePlayer +import de.jeanlucmakiola.floret.ring.isInCall import de.jeanlucmakiola.floret.ring.startRingForeground import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope @@ -23,7 +25,6 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext import javax.inject.Inject /** @@ -33,7 +34,9 @@ import javax.inject.Inject * hands the reminder back to the shade as an ordinary notification. * * One reminder rings at a time. A new one takes over, and the one it replaces - * stays in the shade, silently, unless it was for the same occurrence. + * goes back to the shade, silently, unless it was for the same occurrence. + * Starts and stops both arrive as commands, so they are handled on the main + * thread in the order they were sent. */ @AndroidEntryPoint class ReminderRingService : Service() { @@ -41,6 +44,9 @@ class ReminderRingService : Service() { @Inject lateinit var alerts: FullScreenAlerts @Inject lateinit var notifier: ReminderNotifier + @Inject @ApplicationScope + lateinit var appScope: CoroutineScope + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) private val tones by lazy { TonePlayer(this) } @@ -52,36 +58,36 @@ class ReminderRingService : Service() { private var notificationId = RING_NOTIFICATION_ID private var lastStartId: Int? = null - /** What this service rings, which [FullScreenAlerts.ringing] may already have let go of. */ - private var currentKey: Long? = null - override fun onBind(intent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (intent?.action == ACTION_STOP) { + stop(intent, startId) + return START_NOT_STICKY + } + if (intent?.action == ACTION_RING) { + alerts.pendingStarts.updateAndGet { (it - 1).coerceAtLeast(0) } + } val alert = intent?.let(ReminderActionReceiver::alertFrom) val notification = intent?.let { IntentCompat.getParcelableExtra(it, EXTRA_NOTIFICATION, Notification::class.java) } - if (alerts.starting == alert?.key) alerts.starting = null if (alert == null || notification == null) { - if (alerts.ringing == null) stopSelf() + if (alerts.ringing == null) stopSelfResult(startId) return START_NOT_STICKY } - // Null when the user handled it while this ring was on its way. val previous = alerts.ringing // A different reminder posts under the other id, so it is a new // notification whose full-screen intent opens; an update would not. - val replacing = currentKey != null && currentKey != alert.key + val replacing = previous != null && previous.key != alert.key val shown = notificationId if (replacing) notificationId = if (shown == RING_NOTIFICATION_ID) OTHER_RING_NOTIFICATION_ID else RING_NOTIFICATION_ID val foreground = runCatching { startRingForeground(notificationId, notification) } if (foreground.isFailure) { // A restart after a process death may be refused a foreground start: - // the reminder goes back to the shade rather than being lost. + // the reminder still shows full-screen, sounding once. Log.w(TAG, "Could not ring for event ${alert.eventId}", foreground.exceptionOrNull()) notificationId = shown - scope.launch { - handBack(alert) - if (alerts.ringing == null) stopSelf() - } + handBack(alert, quiet = false) + if (alerts.ringing == null) stopSelfResult(startId) return START_NOT_STICKY } if (replacing) NotificationManagerCompat.from(this).cancel(shown) @@ -89,12 +95,9 @@ class ReminderRingService : Service() { // ones are done, so a handled reminder never rings again. lastStartId?.let { stopSelfResult(it) } lastStartId = startId - if (currentKey == alert.key && timeout?.isActive == true) return START_REDELIVER_INTENT - currentKey = alert.key + if (previous?.key == alert.key && timeout?.isActive == true) return START_REDELIVER_INTENT alerts.ringing = alert - if (previous != null && previous.occurrenceKey != alert.occurrenceKey) { - scope.launch { handBack(previous) } - } + if (previous != null && previous.occurrenceKey != alert.occurrenceKey) handBack(previous) ring() return START_REDELIVER_INTENT } @@ -102,7 +105,6 @@ class ReminderRingService : Service() { override fun onDestroy() { releaseRing() alerts.ringing = null - alerts.starting = null scope.cancel() super.onDestroy() } @@ -112,36 +114,52 @@ class ReminderRingService : Service() { wakeLock.acquire() // Vibration first: the sound may take a moment to open. vibrator.start() - ringing = scope.launch { tones.play(scope, ringSources()) } + // No alarm tone over a phone call; the vibration says enough. + if (!isInCall()) ringing = scope.launch { tones.play(scope, ringSources()) } timeout = scope.launch { delay(RING_TIMEOUT_MILLIS) giveUp() } } - /** Rung long enough: back to the shade quietly, and the alert screen closes. */ - private suspend fun giveUp() { - timeout = null - currentKey = null - val alert = alerts.ringing - releaseRing() - alerts.ringing = null - if (alert != null) { - handBack(alert) - alerts.markHandled(alert) + private fun stop(intent: Intent, startId: Int) { + val current = alerts.ringing + if (current != null && matchFrom(intent).matches(current)) { + if (intent.getBooleanExtra(EXTRA_HAND_BACK, false)) handBack(current) + end() } - stopForeground(STOP_FOREGROUND_REMOVE) - stopSelf() + // Declines while a newer start is still on its way. + if (alerts.ringing == null) stopSelfResult(startId) } - /** [alert] as a quiet notification in the shade, so it is not lost. */ - private suspend fun handBack(alert: ReminderAlert) { - try { - withContext(Dispatchers.IO) { notifier.post(alert, quiet = true) } - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - Log.w(TAG, "Could not hand the reminder of event ${alert.eventId} back", e) + /** Rung long enough: back to the shade quietly. */ + private fun giveUp() { + timeout = null + alerts.ringing?.let(::handBack) + end() + lastStartId?.let { stopSelfResult(it) } + } + + private fun end() { + releaseRing() + alerts.ringing = null + stopForeground(STOP_FOREGROUND_REMOVE) + } + + /** + * [alert] back in the shade, in the app's scope so a service stopped + * meanwhile cannot cancel it, and its alert screen closed. + */ + private fun handBack(alert: ReminderAlert, quiet: Boolean = true) { + alerts.markHandled(alert) + appScope.launch { + try { + notifier.post(alert, quiet = quiet, ring = false) + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Could not hand the reminder of event ${alert.eventId} back", e) + } } } @@ -164,7 +182,12 @@ class ReminderRingService : Service() { companion object { private const val TAG = "ReminderRingService" + private const val ACTION_RING = "de.jeanlucmakiola.calendula.reminders.RING" + private const val ACTION_STOP = "de.jeanlucmakiola.calendula.reminders.RING_STOP" private const val EXTRA_NOTIFICATION = "notification" + private const val EXTRA_MATCH_KIND = "match_kind" + private const val EXTRA_MATCH_VALUE = "match_value" + private const val EXTRA_HAND_BACK = "hand_back" private const val WAKE_LOCK_TAG = "calendula:reminder-ring" /** Clear of the reminders' tagged id 1 and the backup notice's 2. */ @@ -180,23 +203,57 @@ class ReminderRingService : Service() { */ fun start(context: Context, alerts: FullScreenAlerts, alert: ReminderAlert, notification: Notification): Boolean { val intent = Intent(context, ReminderRingService::class.java) + .setAction(ACTION_RING) .putAlert(alert) .putExtra(EXTRA_NOTIFICATION, notification) + alerts.pendingStarts.incrementAndGet() return try { RingWakeLock.handOff(context, WAKE_LOCK_TAG) - alerts.starting = alert.key context.startForegroundService(intent) true } catch (e: Exception) { Log.w(TAG, "Could not start the ring for event ${alert.eventId}", e) - alerts.starting = null + alerts.pendingStarts.updateAndGet { (it - 1).coerceAtLeast(0) } false } } - /** `stopService`, not a command: a command is a start, which can throw from the background. */ - fun stop(context: Context) { - context.stopService(Intent(context, ReminderRingService::class.java)) + /** + * Stops the ring if it is for a reminder [match]es, in order with the + * starts sent before it. [handBack] puts it back in the shade quietly. + * A command rather than `stopService`, which would also drop a start + * still on its way; sent while the ring's foreground service keeps the + * app allowed to. + */ + fun stop(context: Context, match: RingMatch, handBack: Boolean = false) { + val (kind, value) = when (match) { + is RingMatch.Key -> 0 to match.key + is RingMatch.Occurrence -> 1 to match.occurrenceKey + is RingMatch.Calendar -> 2 to match.calendarId + RingMatch.Any -> 3 to 0L + } + val intent = Intent(context, ReminderRingService::class.java) + .setAction(ACTION_STOP) + .putExtra(EXTRA_MATCH_KIND, kind) + .putExtra(EXTRA_MATCH_VALUE, value) + .putExtra(EXTRA_HAND_BACK, handBack) + try { + context.startService(intent) + } catch (e: Exception) { + Log.w(TAG, "Could not stop the ring", e) + // Refused from the background: nothing must ring on regardless. + context.stopService(Intent(context, ReminderRingService::class.java)) + } + } + + private fun matchFrom(intent: Intent): RingMatch { + val value = intent.getLongExtra(EXTRA_MATCH_VALUE, 0L) + return when (intent.getIntExtra(EXTRA_MATCH_KIND, 3)) { + 0 -> RingMatch.Key(value) + 1 -> RingMatch.Occurrence(value) + 2 -> RingMatch.Calendar(value) + else -> RingMatch.Any + } } } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt index a4adc810..5398e598 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt @@ -50,7 +50,7 @@ import javax.inject.Inject /** * The full-screen reminder alert (#171), opened by the reminder's full-screen - * intent over the lock screen, or from its heads-up while the phone is in use. + * intent over the lock screen, or, for a ringing one, from its heads-up. * It stays until the reminder is dismissed or snoozed — here, from the * notification, or by the ring giving up — and back does not close it. */ @@ -68,16 +68,12 @@ class ReminderAlertActivity : ComponentActivity() { private var state by mutableStateOf(ReminderAlertUiState.Loading) private var alert: ReminderAlert? = null private var loading: Job? = null + private var screenOn: Job? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) showOverLockScreen() enableEdgeToEdge() - lifecycleScope.launch { - // An alert nobody answers lets the display sleep again; it stays on the lock screen. - delay(SCREEN_ON_MILLIS) - window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) - } show(intent) lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.CREATED) { @@ -131,6 +127,8 @@ class ReminderAlertActivity : ComponentActivity() { return } alert = next + val ringing = alerts.ringing?.key == next.key + keepScreenOn(if (ringing) ReminderRingService.RING_TIMEOUT_MILLIS else ONCE_SCREEN_ON_MILLIS) loading?.cancel() state = ReminderAlertUiState.Loading loading = lifecycleScope.launch { @@ -153,6 +151,16 @@ class ReminderAlertActivity : ComponentActivity() { } } + /** An alert nobody answers lets the display sleep again; it stays on the lock screen. */ + private fun keepScreenOn(millis: Long) { + window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + screenOn?.cancel() + screenOn = lifecycleScope.launch { + delay(millis) + window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) + } + } + private fun act(action: String) { val current = alert ?: return sendBroadcast(ReminderActionReceiver.intent(this, action, current)) @@ -161,7 +169,7 @@ class ReminderAlertActivity : ComponentActivity() { companion object { private const val TAG = "ReminderAlertActivity" - private const val SCREEN_ON_MILLIS = ReminderRingService.RING_TIMEOUT_MILLIS + private const val ONCE_SCREEN_ON_MILLIS = 60_000L fun intent(context: Context, alert: ReminderAlert): Intent = Intent(context, ReminderAlertActivity::class.java) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt index ea972e6d..dde55087 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt @@ -1,6 +1,9 @@ package de.jeanlucmakiola.calendula.ui.reminders import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -59,55 +62,67 @@ internal fun ReminderAlertScreen( .padding(horizontal = 24.dp, vertical = 32.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { - state.calendarName?.let { - Text( - text = it, - style = MaterialTheme.typography.labelLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - Spacer(Modifier.weight(1f)) - CalendarBadge(state.calendarColor) - Spacer(Modifier.size(32.dp)) - Text( - text = state.title.ifBlank { stringResource(R.string.event_untitled) }, - style = MaterialTheme.typography.displaySmall, - color = MaterialTheme.colorScheme.onSurface, - textAlign = TextAlign.Center, - maxLines = 3, - overflow = TextOverflow.Ellipsis, - ) - Spacer(Modifier.size(12.dp)) - Text( - text = state.time, - style = MaterialTheme.typography.titleLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) - state.location?.let { location -> - Spacer(Modifier.size(8.dp)) - Row(verticalAlignment = Alignment.CenterVertically) { - Icon( - imageVector = Icons.Outlined.LocationOn, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(20.dp), - ) - Spacer(Modifier.size(4.dp)) + // Centred, but scrolls rather than pushing the buttons off a short landscape screen. + BoxWithConstraints(Modifier.weight(1f).fillMaxWidth()) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .heightIn(min = maxHeight), + verticalArrangement = Arrangement.Center, + horizontalAlignment = Alignment.CenterHorizontally, + ) { + state.calendarName?.let { + Text( + text = it, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Spacer(Modifier.size(24.dp)) + } + CalendarBadge(state.calendarColor) + Spacer(Modifier.size(32.dp)) Text( - text = location, - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 2, + text = state.title.ifBlank { stringResource(R.string.event_untitled) }, + style = MaterialTheme.typography.displaySmall, + color = MaterialTheme.colorScheme.onSurface, + textAlign = TextAlign.Center, + maxLines = 3, overflow = TextOverflow.Ellipsis, ) + Spacer(Modifier.size(12.dp)) + Text( + text = state.time, + style = MaterialTheme.typography.titleLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + state.location?.let { location -> + Spacer(Modifier.size(8.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = Icons.Outlined.LocationOn, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(20.dp), + ) + Spacer(Modifier.size(4.dp)) + Text( + text = location, + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } } } - Spacer(Modifier.weight(1.5f)) + Spacer(Modifier.size(24.dp)) Row( - modifier = Modifier.fillMaxWidth().widthIn(max = 480.dp), + modifier = Modifier.widthIn(max = 480.dp).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp), ) { AlertButton( diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt index 48b387c0..cef7545b 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt @@ -18,7 +18,6 @@ import androidx.compose.material.icons.automirrored.filled.OpenInNew import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme 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 @@ -29,9 +28,7 @@ import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.core.net.toUri -import androidx.lifecycle.Lifecycle -import androidx.lifecycle.LifecycleEventObserver -import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.LifecycleResumeEffect import de.jeanlucmakiola.calendula.R import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle @@ -396,7 +393,13 @@ private fun CalendarNotificationRows( ) GroupedRow( title = stringResource(R.string.settings_notification_sound), - summary = stringResource(R.string.settings_calendar_notification_sound_hint), + summary = stringResource( + if (alertStyle == ReminderAlertStyle.FullScreenRing) { + R.string.settings_calendar_notification_sound_ring_hint + } else { + R.string.settings_calendar_notification_sound_hint + }, + ), position = Position.Middle, trailing = { ExternalLinkIcon() }, onClick = onOpenSound, @@ -515,13 +518,9 @@ private fun rememberBatteryOptimizationExempt(): Boolean = rememberOnResume(::is private fun rememberOnResume(read: (Context) -> Boolean): Boolean { val context = LocalContext.current var value by remember { mutableStateOf(read(context)) } - val lifecycleOwner = LocalLifecycleOwner.current - DisposableEffect(lifecycleOwner) { - val observer = LifecycleEventObserver { _, event -> - if (event == Lifecycle.Event.ON_RESUME) value = read(context) - } - lifecycleOwner.lifecycle.addObserver(observer) - onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } + LifecycleResumeEffect(context) { + value = read(context) + onPauseOrDispose {} } return value } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index aa43614a..763d5326 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt @@ -36,6 +36,7 @@ import de.jeanlucmakiola.calendula.data.prefs.TimeFormatPref import de.jeanlucmakiola.calendula.data.prefs.WeekStartPref import de.jeanlucmakiola.calendula.data.reminders.ReminderChannels import de.jeanlucmakiola.calendula.data.reminders.ReminderNotifier +import de.jeanlucmakiola.calendula.data.reminders.RingMatch import de.jeanlucmakiola.calendula.data.reminders.ReminderScanner import de.jeanlucmakiola.calendula.domain.CalendarSource import de.jeanlucmakiola.calendula.domain.reminders.ReminderAlertStyle @@ -362,7 +363,7 @@ class SettingsViewModel @Inject constructor( fun setRemindersEnabled(enabled: Boolean) { viewModelScope.launch { prefs.setRemindersEnabled(enabled) - if (!enabled) reminderNotifier.stopRing { true } + if (!enabled) reminderNotifier.stopRing(RingMatch.Any) reminderScanner.scan() } } @@ -371,14 +372,17 @@ class SettingsViewModel @Inject constructor( fun setCalendarRemindersEnabled(calendarId: Long, enabled: Boolean) { viewModelScope.launch { prefs.setCalendarRemindersEnabled(calendarId, enabled) - if (!enabled) reminderNotifier.stopRing { it.calendarId == calendarId } + if (!enabled) reminderNotifier.stopRing(RingMatch.Calendar(calendarId)) reminderScanner.scan() } } fun setCalendarAlertStyle(calendarId: Long, style: ReminderAlertStyle) { save { setCalendarAlertStyle(calendarId, style) } - if (style != ReminderAlertStyle.FullScreenRing) reminderNotifier.stopRing { it.calendarId == calendarId } + // A ring for it goes quiet but stays in the shade. + if (style != ReminderAlertStyle.FullScreenRing) { + reminderNotifier.stopRing(RingMatch.Calendar(calendarId), handBack = true) + } } /** [calendarId]'s reminder channel, created if needed so its system settings can open (#340). */ diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3e0ffec5..e9252d1c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -749,7 +749,8 @@ Play sound once This calendar\'s notification sound, once Ring until dismissed - Your alarm sound and vibration, like an alarm + Your alarm sound and vibration, like an alarm, also in Do Not Disturb when alarms may sound + Ringing reminders use your alarm sound. This sets the sound of the ones handed back to the shade. Allow full-screen alerts Android blocks Calendula\'s full-screen alerts, so they only pop up as notifications. Tap to allow them. Default (%1$s) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 861ec3dc..45ac53f0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -420,9 +420,13 @@ foreground on the shared silent `reminders_ring` channel and loops the alarm sound with vibration through floret-kit's `ring` module — the same player Clockula's alarms use. One reminder rings at a time; a newer one takes over and hands the older back to the shade quietly, as does a ring left unanswered for -ten minutes. Dismiss and Snooze, from the screen, the notification or a swipe, -all go through `ReminderActionReceiver`, so the ring stops and the screen -closes (`FullScreenAlerts`) however the reminder was handled. When Android 14+ +ten minutes, and switching the calendar away from ringing. Dismiss and Snooze, +from the screen, the notification or a swipe, all go through +`ReminderActionReceiver`, so the ring stops and the screen closes +(`FullScreenAlerts`) however the reminder was handled. Starts and stops reach +the service as commands, so a dismiss sent while a newer ring is on its way +applies in order rather than killing it. A blocked calendar, account group or +ring channel never rings, and during a call the ring only vibrates. When Android 14+ withholds `USE_FULL_SCREEN_INTENT`, the intent is left off and the alert is a heads-up; Settings shows a row leading to the system switch. When Android refuses the ring service, the reminder falls back to sounding once. diff --git a/floret-kit b/floret-kit index b1401bcf..7a5b81e8 160000 --- a/floret-kit +++ b/floret-kit @@ -1 +1 @@ -Subproject commit b1401bcf6a76f675bf1b53bb4da5b1be8971757e +Subproject commit 7a5b81e88a24910b80dc21c4ef16cc2c94282a5f From 4287862f47c50277f580a27403364d8cc8029313 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 17:45:25 +0100 Subject: [PATCH 05/11] chore(#171): floret-kit ring fixes --- floret-kit | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/floret-kit b/floret-kit index 7a5b81e8..1c6c96fe 160000 --- a/floret-kit +++ b/floret-kit @@ -1 +1 @@ -Subproject commit 7a5b81e88a24910b80dc21c4ef16cc2c94282a5f +Subproject commit 1c6c96fe33ef32692948aa8c603091737e99390f From 014d31f9b9a6b5d136cf4d3465ea3cfdb0a2fc20 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 17:56:11 +0100 Subject: [PATCH 06/11] fix(#171): review round 3 - re-check settings in the ring, follow calls, anchored timeout, close the screen on every stop --- .../data/reminders/FullScreenAlerts.kt | 3 + .../data/reminders/ReminderNotifier.kt | 11 +- .../data/reminders/ReminderRingService.kt | 101 +++++++++++++----- .../ui/reminders/ReminderAlertActivity.kt | 3 +- .../ui/settings/SettingsViewModel.kt | 10 +- docs/ARCHITECTURE.md | 7 +- 6 files changed, 103 insertions(+), 32 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt index 71947ae8..9c2fac71 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt @@ -40,6 +40,9 @@ class FullScreenAlerts @Inject constructor() { } } +/** What becomes of a ring once its settings are re-read. */ +enum class RingVerdict { Ring, HandBack, Drop } + /** Which ring a stop is for. */ sealed interface RingMatch { fun matches(alert: ReminderAlert): Boolean diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index 2e446bfc..17692ff6 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt @@ -96,6 +96,7 @@ class ReminderNotifier @Inject constructor( return } // Android refused the ring: still full-screen, sounding once on the calendar's channel. + stopRing(RingMatch.Occurrence(alert.occurrenceKey)) val fallback = channelFor(alert, ReminderAlertStyle.FullScreen) ?: return notify(alert, build(alert, fallback, title, text, ReminderAlertStyle.FullScreen, quiet)) return @@ -105,6 +106,14 @@ class ReminderNotifier @Inject constructor( notify(alert, build(alert, channelId, title, text, style, quiet)) } + /** Whether a ring for [alert] should go on, now that settings may have changed since it started. */ + suspend fun ringVerdict(alert: ReminderAlert): RingVerdict = when { + !settingsPrefs.remindersEnabled.first() || isSilenced(alert.calendarId) -> RingVerdict.Drop + settingsPrefs.reminderAlertStyles.first().alertStyleFor(alert.calendarId) != ReminderAlertStyle.FullScreenRing || + !channels.canRing(alert.calendarId) -> RingVerdict.HandBack + else -> RingVerdict.Ring + } + private fun channelFor(alert: ReminderAlert, style: ReminderAlertStyle): String? = try { channels.channelFor(alert.calendarId, style) } catch (e: Exception) { @@ -214,7 +223,7 @@ class ReminderNotifier @Inject constructor( /** Stop the ring if it is for a reminder [match]es; [handBack] keeps it in the shade, quietly. */ fun stopRing(match: RingMatch, handBack: Boolean = false) { - if (alerts.mayBeRinging) ReminderRingService.stop(context, match, handBack) + if (alerts.mayBeRinging) ReminderRingService.stop(context, alerts, match, handBack) } /** Whether a different reminder for [alert]'s occurrence is on screen now. */ diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt index 8a167daf..af5eb259 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt @@ -25,6 +25,7 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext import javax.inject.Inject /** @@ -58,20 +59,26 @@ class ReminderRingService : Service() { private var notificationId = RING_NOTIFICATION_ID private var lastStartId: Int? = null + /** Whether the ring's players were ever built, so a stop-only service builds none. */ + private var rang = false + override fun onBind(intent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + val previousStart = lastStartId + lastStartId = startId if (intent?.action == ACTION_STOP) { - stop(intent, startId) + stop(intent) return START_NOT_STICKY } - if (intent?.action == ACTION_RING) { + // A redelivered start was never counted by this process. + if (intent?.action == ACTION_RING && flags and START_FLAG_REDELIVERY == 0) { alerts.pendingStarts.updateAndGet { (it - 1).coerceAtLeast(0) } } val alert = intent?.let(ReminderActionReceiver::alertFrom) val notification = intent?.let { IntentCompat.getParcelableExtra(it, EXTRA_NOTIFICATION, Notification::class.java) } if (alert == null || notification == null) { - if (alerts.ringing == null) stopSelfResult(startId) + stopIfIdle() return START_NOT_STICKY } val previous = alerts.ringing @@ -87,49 +94,83 @@ class ReminderRingService : Service() { Log.w(TAG, "Could not ring for event ${alert.eventId}", foreground.exceptionOrNull()) notificationId = shown handBack(alert, quiet = false) - if (alerts.ringing == null) stopSelfResult(startId) + stopIfIdle() return START_NOT_STICKY } if (replacing) NotificationManagerCompat.from(this).cancel(shown) // Only the newest start is redelivered after a process death; the older // ones are done, so a handled reminder never rings again. - lastStartId?.let { stopSelfResult(it) } - lastStartId = startId - if (previous?.key == alert.key && timeout?.isActive == true) return START_REDELIVER_INTENT + previousStart?.let { stopSelfResult(it) } + if (previous?.key == alert.key) return START_REDELIVER_INTENT alerts.ringing = alert - if (previous != null && previous.occurrenceKey != alert.occurrenceKey) handBack(previous) - ring() + if (previous != null) { + // Its screen closes either way; another occurrence goes back to the shade. + if (previous.occurrenceKey != alert.occurrenceKey) handBack(previous) else alerts.markHandled(previous) + } + val since = intent.getLongExtra(EXTRA_SINCE, System.currentTimeMillis()) + ring(alert, remaining = since + RING_TIMEOUT_MILLIS - System.currentTimeMillis()) return START_REDELIVER_INTENT } override fun onDestroy() { - releaseRing() + if (rang) releaseRing() alerts.ringing = null scope.cancel() super.onDestroy() } - private fun ring() { + /** Rings for what is left of the ring's time, so a ring restarted after a process death does not begin again. */ + private fun ring(alert: ReminderAlert, remaining: Long) { releaseRing() + rang = true wakeLock.acquire() // Vibration first: the sound may take a moment to open. vibrator.start() - // No alarm tone over a phone call; the vibration says enough. - if (!isInCall()) ringing = scope.launch { tones.play(scope, ringSources()) } + ringing = scope.launch { followCalls() } timeout = scope.launch { - delay(RING_TIMEOUT_MILLIS) + delay(remaining.coerceAtLeast(0L)) giveUp() } + // Settings changed while this ring was on its way apply to it too. + scope.launch { + val verdict = try { + withContext(Dispatchers.IO) { notifier.ringVerdict(alert) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Could not re-check the ring for event ${alert.eventId}", e) + RingVerdict.Ring + } + if (alerts.ringing?.key != alert.key || verdict == RingVerdict.Ring) return@launch + if (verdict == RingVerdict.HandBack) handBack(alert) + end() + stopIfIdle() + } } - private fun stop(intent: Intent, startId: Int) { + /** The tone, but never over a phone call: it stops for one and comes back after. */ + private suspend fun followCalls() { + var playing = false + while (true) { + val inCall = isInCall() + if (inCall && playing) { + tones.stop() + playing = false + } else if (!inCall && !playing) { + tones.play(scope, ringSources()) + playing = true + } + delay(CALL_CHECK_MILLIS) + } + } + + private fun stop(intent: Intent) { val current = alerts.ringing if (current != null && matchFrom(intent).matches(current)) { if (intent.getBooleanExtra(EXTRA_HAND_BACK, false)) handBack(current) end() } - // Declines while a newer start is still on its way. - if (alerts.ringing == null) stopSelfResult(startId) + stopIfIdle() } /** Rung long enough: back to the shade quietly. */ @@ -137,24 +178,32 @@ class ReminderRingService : Service() { timeout = null alerts.ringing?.let(::handBack) end() - lastStartId?.let { stopSelfResult(it) } + stopIfIdle() } + /** Ends the ring and closes its screen. */ private fun end() { + alerts.ringing?.let(alerts::markHandled) releaseRing() alerts.ringing = null stopForeground(STOP_FOREGROUND_REMOVE) } + /** Declines while a newer command is still on its way. */ + private fun stopIfIdle() { + if (alerts.ringing == null) lastStartId?.let { stopSelfResult(it) } + } + /** * [alert] back in the shade, in the app's scope so a service stopped - * meanwhile cannot cancel it, and its alert screen closed. + * meanwhile cannot cancel it, and its alert screen closed. A newer reminder + * for the occurrence that took its place meanwhile is left alone. */ private fun handBack(alert: ReminderAlert, quiet: Boolean = true) { alerts.markHandled(alert) appScope.launch { try { - notifier.post(alert, quiet = quiet, ring = false) + if (!notifier.isSuperseded(alert)) notifier.post(alert, quiet = quiet, ring = false) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -173,11 +222,10 @@ class ReminderRingService : Service() { wakeLock.release() } - /** The device's alarm sound, then the built-in ones; none opening leaves the vibration. */ + /** The device's alarm sound; "None", or none opening, leaves the vibration. */ private fun ringSources() = listOfNotNull( RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM), - RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), ) companion object { @@ -185,6 +233,8 @@ class ReminderRingService : Service() { private const val ACTION_RING = "de.jeanlucmakiola.calendula.reminders.RING" private const val ACTION_STOP = "de.jeanlucmakiola.calendula.reminders.RING_STOP" private const val EXTRA_NOTIFICATION = "notification" + private const val EXTRA_SINCE = "since" + private const val CALL_CHECK_MILLIS = 1_000L private const val EXTRA_MATCH_KIND = "match_kind" private const val EXTRA_MATCH_VALUE = "match_value" private const val EXTRA_HAND_BACK = "hand_back" @@ -206,6 +256,7 @@ class ReminderRingService : Service() { .setAction(ACTION_RING) .putAlert(alert) .putExtra(EXTRA_NOTIFICATION, notification) + .putExtra(EXTRA_SINCE, System.currentTimeMillis()) alerts.pendingStarts.incrementAndGet() return try { RingWakeLock.handOff(context, WAKE_LOCK_TAG) @@ -225,7 +276,7 @@ class ReminderRingService : Service() { * still on its way; sent while the ring's foreground service keeps the * app allowed to. */ - fun stop(context: Context, match: RingMatch, handBack: Boolean = false) { + fun stop(context: Context, alerts: FullScreenAlerts, match: RingMatch, handBack: Boolean = false) { val (kind, value) = when (match) { is RingMatch.Key -> 0 to match.key is RingMatch.Occurrence -> 1 to match.occurrenceKey @@ -241,8 +292,10 @@ class ReminderRingService : Service() { context.startService(intent) } catch (e: Exception) { Log.w(TAG, "Could not stop the ring", e) - // Refused from the background: nothing must ring on regardless. + // Refused from the background: nothing must ring on regardless, + // and the starts this drops will never arrive. context.stopService(Intent(context, ReminderRingService::class.java)) + alerts.pendingStarts.set(0) } } diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt index 5398e598..e132b4d3 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertActivity.kt @@ -127,7 +127,8 @@ class ReminderAlertActivity : ComponentActivity() { return } alert = next - val ringing = alerts.ringing?.key == next.key + // A ring still going, this one's or another's, keeps the screen up as long as it rings. + val ringing = alerts.ringing != null keepScreenOn(if (ringing) ReminderRingService.RING_TIMEOUT_MILLIS else ONCE_SCREEN_ON_MILLIS) loading?.cancel() state = ReminderAlertUiState.Loading diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index 763d5326..265a22df 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt @@ -378,10 +378,12 @@ class SettingsViewModel @Inject constructor( } fun setCalendarAlertStyle(calendarId: Long, style: ReminderAlertStyle) { - save { setCalendarAlertStyle(calendarId, style) } - // A ring for it goes quiet but stays in the shade. - if (style != ReminderAlertStyle.FullScreenRing) { - reminderNotifier.stopRing(RingMatch.Calendar(calendarId), handBack = true) + viewModelScope.launch { + prefs.setCalendarAlertStyle(calendarId, style) + // A ring for it goes quiet but stays in the shade. + if (style != ReminderAlertStyle.FullScreenRing) { + reminderNotifier.stopRing(RingMatch.Calendar(calendarId), handBack = true) + } } } diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 45ac53f0..ceb3ae50 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -425,8 +425,11 @@ from the screen, the notification or a swipe, all go through `ReminderActionReceiver`, so the ring stops and the screen closes (`FullScreenAlerts`) however the reminder was handled. Starts and stops reach the service as commands, so a dismiss sent while a newer ring is on its way -applies in order rather than killing it. A blocked calendar, account group or -ring channel never rings, and during a call the ring only vibrates. When Android 14+ +applies in order rather than killing it, and the service re-reads the settings +once a ring arrives, so a style change or mute that raced a scan still wins. A +blocked calendar, account group or ring channel never rings, the tone pauses +for a phone call, and a ring restarted after a process death only rings out +what was left of its ten minutes. When Android 14+ withholds `USE_FULL_SCREEN_INTENT`, the intent is left off and the alert is a heads-up; Settings shows a row leading to the system switch. When Android refuses the ring service, the reminder falls back to sounding once. From 0b6cdf992ec9af17765b1f36453458e5a3182a0a Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 18:06:17 +0100 Subject: [PATCH 07/11] fix(#171): review round 4 - targeted ring stops, verdict before any sound, stop when the ring notification is hidden, no re-ring of a handed-back reminder --- .../data/reminders/FullScreenAlerts.kt | 11 +-- .../data/reminders/ReminderNotifier.kt | 34 +++++++--- .../data/reminders/ReminderRingService.kt | 68 ++++++++++++------- 3 files changed, 71 insertions(+), 42 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt index 9c2fac71..2414a709 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt @@ -4,7 +4,7 @@ import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.asSharedFlow -import java.util.concurrent.atomic.AtomicInteger +import java.util.concurrent.ConcurrentHashMap import javax.inject.Inject import javax.inject.Singleton @@ -21,11 +21,12 @@ class FullScreenAlerts @Inject constructor() { var ringing: ReminderAlert? = null internal set - /** Rings handed to [ReminderRingService] that have not reached it yet. */ - internal val pendingStarts = AtomicInteger(0) + /** Rings handed to [ReminderRingService] that have not reached it yet, by key. */ + internal val pending = ConcurrentHashMap() - /** Whether a ring is going or on its way, so a stop is worth sending. */ - val mayBeRinging: Boolean get() = ringing != null || pendingStarts.get() > 0 + /** Whether a ring going or on its way [match]es, so a stop is worth sending. */ + fun mayRing(match: RingMatch): Boolean = + ringing?.let(match::matches) == true || pending.values.any(match::matches) private val handledKeys = MutableSharedFlow( extraBufferCapacity = 8, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index 17692ff6..d152982a 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt @@ -77,19 +77,19 @@ class ReminderNotifier @Inject constructor( */ suspend fun post(alert: ReminderAlert, quiet: Boolean = false, ring: Boolean = true) { if (isSilenced(alert.calendarId)) return - val chosen = settingsPrefs.reminderAlertStyles.first().alertStyleFor(alert.calendarId) val style = when { quiet -> ReminderAlertStyle.Notification - // A calendar or ring channel the user blocked must not ring regardless. - chosen == ReminderAlertStyle.FullScreenRing && (!ring || !channels.canRing(alert.calendarId)) -> - ReminderAlertStyle.FullScreen - else -> chosen + else -> effectiveStyle(alert).let { + if (it == ReminderAlertStyle.FullScreenRing && !ring) ReminderAlertStyle.FullScreen else it + } } + // Rung already and handed back to the shade: a catch-up post leaves it there. + if (style == ReminderAlertStyle.FullScreenRing && isShowing(alert)) return val channelId = channelFor(alert, style) ?: return val title = displayTitle(alert) val text = contentText(alert) if (style == ReminderAlertStyle.FullScreenRing) { - if (ReminderRingService.start(context, alerts, alert, build(alert, channelId, title, text, style, quiet))) { + if (ReminderRingService.start(context, alerts, alert, build(alert, channelId, title, text, style, quiet = false))) { // An earlier reminder for this occurrence gives way to the ring. NotificationManagerCompat.from(context).cancel(alert.occurrenceKey.toString(), NOTIFICATION_ID) cancelLegacy(alert) @@ -98,7 +98,7 @@ class ReminderNotifier @Inject constructor( // Android refused the ring: still full-screen, sounding once on the calendar's channel. stopRing(RingMatch.Occurrence(alert.occurrenceKey)) val fallback = channelFor(alert, ReminderAlertStyle.FullScreen) ?: return - notify(alert, build(alert, fallback, title, text, ReminderAlertStyle.FullScreen, quiet)) + notify(alert, build(alert, fallback, title, text, ReminderAlertStyle.FullScreen, quiet = false)) return } // A fresh reminder replaces a ring for its occurrence from before the style changed. @@ -108,12 +108,24 @@ class ReminderNotifier @Inject constructor( /** Whether a ring for [alert] should go on, now that settings may have changed since it started. */ suspend fun ringVerdict(alert: ReminderAlert): RingVerdict = when { - !settingsPrefs.remindersEnabled.first() || isSilenced(alert.calendarId) -> RingVerdict.Drop - settingsPrefs.reminderAlertStyles.first().alertStyleFor(alert.calendarId) != ReminderAlertStyle.FullScreenRing || - !channels.canRing(alert.calendarId) -> RingVerdict.HandBack + !settingsPrefs.remindersEnabled.first() || !canPost() || isSilenced(alert.calendarId) -> RingVerdict.Drop + effectiveStyle(alert) != ReminderAlertStyle.FullScreenRing -> RingVerdict.HandBack else -> RingVerdict.Ring } + /** Whether a live ring for [alert] may go on: its notification can still be seen. */ + fun canStillRing(alert: ReminderAlert): Boolean = canPost() && channels.canRing(alert.calendarId) + + /** The calendar's style, short of ringing where the user blocked its calendar, group or the ring channel. */ + private suspend fun effectiveStyle(alert: ReminderAlert): ReminderAlertStyle { + val chosen = settingsPrefs.reminderAlertStyles.first().alertStyleFor(alert.calendarId) + return if (chosen == ReminderAlertStyle.FullScreenRing && !channels.canRing(alert.calendarId)) { + ReminderAlertStyle.FullScreen + } else { + chosen + } + } + private fun channelFor(alert: ReminderAlert, style: ReminderAlertStyle): String? = try { channels.channelFor(alert.calendarId, style) } catch (e: Exception) { @@ -223,7 +235,7 @@ class ReminderNotifier @Inject constructor( /** Stop the ring if it is for a reminder [match]es; [handBack] keeps it in the shade, quietly. */ fun stopRing(match: RingMatch, handBack: Boolean = false) { - if (alerts.mayBeRinging) ReminderRingService.stop(context, alerts, match, handBack) + if (alerts.mayRing(match)) ReminderRingService.stop(context, alerts, match, handBack) } /** Whether a different reminder for [alert]'s occurrence is on screen now. */ diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt index af5eb259..f82c3507 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt @@ -71,11 +71,16 @@ class ReminderRingService : Service() { stop(intent) return START_NOT_STICKY } - // A redelivered start was never counted by this process. - if (intent?.action == ACTION_RING && flags and START_FLAG_REDELIVERY == 0) { - alerts.pendingStarts.updateAndGet { (it - 1).coerceAtLeast(0) } - } val alert = intent?.let(ReminderActionReceiver::alertFrom) + try { + return startRing(intent, alert, previousStart) + } finally { + // Only now, once alerts.ringing says whether it rings, so a stop sent meanwhile is never skipped. + alert?.let { alerts.pending.remove(it.key) } + } + } + + private fun startRing(intent: Intent?, alert: ReminderAlert?, previousStart: Int?): Int { val notification = intent?.let { IntentCompat.getParcelableExtra(it, EXTRA_NOTIFICATION, Notification::class.java) } if (alert == null || notification == null) { stopIfIdle() @@ -107,13 +112,15 @@ class ReminderRingService : Service() { // Its screen closes either way; another occurrence goes back to the shade. if (previous.occurrenceKey != alert.occurrenceKey) handBack(previous) else alerts.markHandled(previous) } - val since = intent.getLongExtra(EXTRA_SINCE, System.currentTimeMillis()) + val since = intent?.getLongExtra(EXTRA_SINCE, System.currentTimeMillis()) ?: System.currentTimeMillis() ring(alert, remaining = since + RING_TIMEOUT_MILLIS - System.currentTimeMillis()) return START_REDELIVER_INTENT } override fun onDestroy() { if (rang) releaseRing() + // Stopped from outside: its screen must not stay up for a ring that is gone. + alerts.ringing?.let(alerts::markHandled) alerts.ringing = null scope.cancel() super.onDestroy() @@ -124,15 +131,12 @@ class ReminderRingService : Service() { releaseRing() rang = true wakeLock.acquire() - // Vibration first: the sound may take a moment to open. - vibrator.start() - ringing = scope.launch { followCalls() } timeout = scope.launch { delay(remaining.coerceAtLeast(0L)) giveUp() } - // Settings changed while this ring was on its way apply to it too. - scope.launch { + ringing = scope.launch { + // Settings changed while this ring was on its way apply before it makes a sound. val verdict = try { withContext(Dispatchers.IO) { notifier.ringVerdict(alert) } } catch (e: CancellationException) { @@ -141,24 +145,37 @@ class ReminderRingService : Service() { Log.w(TAG, "Could not re-check the ring for event ${alert.eventId}", e) RingVerdict.Ring } - if (alerts.ringing?.key != alert.key || verdict == RingVerdict.Ring) return@launch - if (verdict == RingVerdict.HandBack) handBack(alert) - end() - stopIfIdle() + if (verdict != RingVerdict.Ring) { + if (verdict == RingVerdict.HandBack) handBack(alert) + end() + stopIfIdle() + return@launch + } + sound(alert) } } - /** The tone, but never over a phone call: it stops for one and comes back after. */ - private suspend fun followCalls() { - var playing = false + /** + * Tone and vibration, paused for a phone call and back after it, until the + * user hides the ring's notification, which would leave no way to stop it. + */ + private suspend fun sound(alert: ReminderAlert) { + var sounding = false while (true) { + if (!notifier.canStillRing(alert)) { + end() + stopIfIdle() + return + } val inCall = isInCall() - if (inCall && playing) { + if (inCall && sounding) { tones.stop() - playing = false - } else if (!inCall && !playing) { + vibrator.stop() + sounding = false + } else if (!inCall && !sounding) { + vibrator.start() tones.play(scope, ringSources()) - playing = true + sounding = true } delay(CALL_CHECK_MILLIS) } @@ -257,14 +274,14 @@ class ReminderRingService : Service() { .putAlert(alert) .putExtra(EXTRA_NOTIFICATION, notification) .putExtra(EXTRA_SINCE, System.currentTimeMillis()) - alerts.pendingStarts.incrementAndGet() + alerts.pending[alert.key] = alert return try { RingWakeLock.handOff(context, WAKE_LOCK_TAG) context.startForegroundService(intent) true } catch (e: Exception) { Log.w(TAG, "Could not start the ring for event ${alert.eventId}", e) - alerts.pendingStarts.updateAndGet { (it - 1).coerceAtLeast(0) } + alerts.pending.remove(alert.key) false } } @@ -293,9 +310,8 @@ class ReminderRingService : Service() { } catch (e: Exception) { Log.w(TAG, "Could not stop the ring", e) // Refused from the background: nothing must ring on regardless, - // and the starts this drops will never arrive. - context.stopService(Intent(context, ReminderRingService::class.java)) - alerts.pendingStarts.set(0) + // unless a start is still on its way, which this would crash. + if (alerts.pending.isEmpty()) context.stopService(Intent(context, ReminderRingService::class.java)) } } From 9178828b41a467225a18b8461192a1134df49f5f Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 18:13:27 +0100 Subject: [PATCH 08/11] fix(#171): review round 5 - hand back on a hidden ring, counted pending starts, keep the first start's redelivery --- .../data/reminders/FullScreenAlerts.kt | 27 +++++++++-- .../data/reminders/ReminderNotifier.kt | 2 +- .../data/reminders/ReminderRingService.kt | 48 ++++++++++++------- 3 files changed, 55 insertions(+), 22 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt index 2414a709..cfc415eb 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/FullScreenAlerts.kt @@ -21,12 +21,31 @@ class FullScreenAlerts @Inject constructor() { var ringing: ReminderAlert? = null internal set - /** Rings handed to [ReminderRingService] that have not reached it yet, by key. */ - internal val pending = ConcurrentHashMap() + /** Rings handed to [ReminderRingService] that have not reached it yet, with how many starts each. */ + private val pending = ConcurrentHashMap>() - /** Whether a ring going or on its way [match]es, so a stop is worth sending. */ + /** Set when the service is stopped from outside but its ring should go back to the shade. */ + @Volatile + internal var handBackOnDestroy = false + + internal fun addPending(alert: ReminderAlert) { + pending.compute(alert.key) { _, entry -> alert to ((entry?.second ?: 0) + 1) } + } + + internal fun removePending(alert: ReminderAlert) { + pending.computeIfPresent(alert.key) { _, entry -> if (entry.second <= 1) null else entry.first to entry.second - 1 } + } + + internal fun isPending(alert: ReminderAlert): Boolean = pending.containsKey(alert.key) + + internal val anyPending: Boolean get() = pending.isNotEmpty() + + /** + * Whether a ring going or on its way [match]es, so a stop is worth sending. + * Pending first: the service sets [ringing] before it lets a start go. + */ fun mayRing(match: RingMatch): Boolean = - ringing?.let(match::matches) == true || pending.values.any(match::matches) + pending.values.any { match.matches(it.first) } || ringing?.let(match::matches) == true private val handledKeys = MutableSharedFlow( extraBufferCapacity = 8, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index d152982a..bdea773d 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt @@ -84,7 +84,7 @@ class ReminderNotifier @Inject constructor( } } // Rung already and handed back to the shade: a catch-up post leaves it there. - if (style == ReminderAlertStyle.FullScreenRing && isShowing(alert)) return + if (style == ReminderAlertStyle.FullScreenRing && (isShowing(alert) || alerts.isPending(alert))) return val channelId = channelFor(alert, style) ?: return val title = displayTitle(alert) val text = contentText(alert) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt index f82c3507..5181789c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt @@ -72,17 +72,21 @@ class ReminderRingService : Service() { return START_NOT_STICKY } val alert = intent?.let(ReminderActionReceiver::alertFrom) + if (intent == null || alert == null) { + stopIfIdle() + return START_NOT_STICKY + } try { return startRing(intent, alert, previousStart) } finally { // Only now, once alerts.ringing says whether it rings, so a stop sent meanwhile is never skipped. - alert?.let { alerts.pending.remove(it.key) } + if (flags and START_FLAG_REDELIVERY == 0) alerts.removePending(alert) } } - private fun startRing(intent: Intent?, alert: ReminderAlert?, previousStart: Int?): Int { - val notification = intent?.let { IntentCompat.getParcelableExtra(it, EXTRA_NOTIFICATION, Notification::class.java) } - if (alert == null || notification == null) { + private fun startRing(intent: Intent, alert: ReminderAlert, previousStart: Int?): Int { + val notification = IntentCompat.getParcelableExtra(intent, EXTRA_NOTIFICATION, Notification::class.java) + if (notification == null) { stopIfIdle() return START_NOT_STICKY } @@ -103,16 +107,17 @@ class ReminderRingService : Service() { return START_NOT_STICKY } if (replacing) NotificationManagerCompat.from(this).cancel(shown) + // A duplicate start for this very ring leaves the original in charge of redelivery. + if (previous?.key == alert.key) return START_NOT_STICKY // Only the newest start is redelivered after a process death; the older // ones are done, so a handled reminder never rings again. previousStart?.let { stopSelfResult(it) } - if (previous?.key == alert.key) return START_REDELIVER_INTENT alerts.ringing = alert if (previous != null) { // Its screen closes either way; another occurrence goes back to the shade. if (previous.occurrenceKey != alert.occurrenceKey) handBack(previous) else alerts.markHandled(previous) } - val since = intent?.getLongExtra(EXTRA_SINCE, System.currentTimeMillis()) ?: System.currentTimeMillis() + val since = intent.getLongExtra(EXTRA_SINCE, System.currentTimeMillis()) ring(alert, remaining = since + RING_TIMEOUT_MILLIS - System.currentTimeMillis()) return START_REDELIVER_INTENT } @@ -120,7 +125,8 @@ class ReminderRingService : Service() { override fun onDestroy() { if (rang) releaseRing() // Stopped from outside: its screen must not stay up for a ring that is gone. - alerts.ringing?.let(alerts::markHandled) + alerts.ringing?.let { if (alerts.handBackOnDestroy) handBack(it) else alerts.markHandled(it) } + alerts.handBackOnDestroy = false alerts.ringing = null scope.cancel() super.onDestroy() @@ -146,9 +152,9 @@ class ReminderRingService : Service() { RingVerdict.Ring } if (verdict != RingVerdict.Ring) { - if (verdict == RingVerdict.HandBack) handBack(alert) + // Never heard yet, so it alerts once in its new style. + if (verdict == RingVerdict.HandBack) handBack(alert, quiet = false) end() - stopIfIdle() return@launch } sound(alert) @@ -161,10 +167,11 @@ class ReminderRingService : Service() { */ private suspend fun sound(alert: ReminderAlert) { var sounding = false + var tick = 0 while (true) { - if (!notifier.canStillRing(alert)) { + if (tick++ % VISIBILITY_CHECK_TICKS == 0 && !notifier.canStillRing(alert)) { + handBack(alert) end() - stopIfIdle() return } val inCall = isInCall() @@ -186,8 +193,9 @@ class ReminderRingService : Service() { if (current != null && matchFrom(intent).matches(current)) { if (intent.getBooleanExtra(EXTRA_HAND_BACK, false)) handBack(current) end() + } else { + stopIfIdle() } - stopIfIdle() } /** Rung long enough: back to the shade quietly. */ @@ -195,15 +203,15 @@ class ReminderRingService : Service() { timeout = null alerts.ringing?.let(::handBack) end() - stopIfIdle() } - /** Ends the ring and closes its screen. */ + /** Ends the ring, closes its screen, and stops the service unless a newer command is on its way. */ private fun end() { alerts.ringing?.let(alerts::markHandled) releaseRing() alerts.ringing = null stopForeground(STOP_FOREGROUND_REMOVE) + stopIfIdle() } /** Declines while a newer command is still on its way. */ @@ -252,6 +260,9 @@ class ReminderRingService : Service() { private const val EXTRA_NOTIFICATION = "notification" private const val EXTRA_SINCE = "since" private const val CALL_CHECK_MILLIS = 1_000L + + /** How many call checks between re-reading whether the ring's notification can still be seen. */ + private const val VISIBILITY_CHECK_TICKS = 5 private const val EXTRA_MATCH_KIND = "match_kind" private const val EXTRA_MATCH_VALUE = "match_value" private const val EXTRA_HAND_BACK = "hand_back" @@ -274,14 +285,14 @@ class ReminderRingService : Service() { .putAlert(alert) .putExtra(EXTRA_NOTIFICATION, notification) .putExtra(EXTRA_SINCE, System.currentTimeMillis()) - alerts.pending[alert.key] = alert + alerts.addPending(alert) return try { RingWakeLock.handOff(context, WAKE_LOCK_TAG) context.startForegroundService(intent) true } catch (e: Exception) { Log.w(TAG, "Could not start the ring for event ${alert.eventId}", e) - alerts.pending.remove(alert.key) + alerts.removePending(alert) false } } @@ -311,7 +322,10 @@ class ReminderRingService : Service() { Log.w(TAG, "Could not stop the ring", e) // Refused from the background: nothing must ring on regardless, // unless a start is still on its way, which this would crash. - if (alerts.pending.isEmpty()) context.stopService(Intent(context, ReminderRingService::class.java)) + if (!alerts.anyPending) { + alerts.handBackOnDestroy = handBack + context.stopService(Intent(context, ReminderRingService::class.java)) + } } } From 7361e8d98e413337cc71b83a37a62365ec019502 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 18:18:04 +0100 Subject: [PATCH 09/11] fix(#171): review round 6 - mark the redeliverable start done on takeover --- .../calendula/data/reminders/ReminderRingService.kt | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt index 5181789c..93aaaa91 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt @@ -59,13 +59,15 @@ class ReminderRingService : Service() { private var notificationId = RING_NOTIFICATION_ID private var lastStartId: Int? = null + /** The start the system would redeliver, so a takeover can mark it done. */ + private var ringStartId: Int? = null + /** Whether the ring's players were ever built, so a stop-only service builds none. */ private var rang = false override fun onBind(intent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { - val previousStart = lastStartId lastStartId = startId if (intent?.action == ACTION_STOP) { stop(intent) @@ -77,14 +79,14 @@ class ReminderRingService : Service() { return START_NOT_STICKY } try { - return startRing(intent, alert, previousStart) + return startRing(intent, alert, startId) } finally { // Only now, once alerts.ringing says whether it rings, so a stop sent meanwhile is never skipped. if (flags and START_FLAG_REDELIVERY == 0) alerts.removePending(alert) } } - private fun startRing(intent: Intent, alert: ReminderAlert, previousStart: Int?): Int { + private fun startRing(intent: Intent, alert: ReminderAlert, startId: Int): Int { val notification = IntentCompat.getParcelableExtra(intent, EXTRA_NOTIFICATION, Notification::class.java) if (notification == null) { stopIfIdle() @@ -111,7 +113,8 @@ class ReminderRingService : Service() { if (previous?.key == alert.key) return START_NOT_STICKY // Only the newest start is redelivered after a process death; the older // ones are done, so a handled reminder never rings again. - previousStart?.let { stopSelfResult(it) } + ringStartId?.let { stopSelfResult(it) } + ringStartId = startId alerts.ringing = alert if (previous != null) { // Its screen closes either way; another occurrence goes back to the shade. From f181ae7ac920e853f72da147329d9789ac702cdd Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Sat, 14 Nov 2026 03:10:20 +0100 Subject: [PATCH 10/11] fix(#171): merge review - ring channel up front, held-back status in the calendar header, silenced calendars stop a live ring --- .../data/reminders/ReminderChannels.kt | 32 +++++++++------- .../data/reminders/ReminderNotifier.kt | 19 +++++++--- .../data/reminders/ReminderRingService.kt | 11 +++++- .../ui/settings/NotificationSettings.kt | 37 ++++++++++++++++--- .../ui/settings/SettingsViewModel.kt | 11 +++++- app/src/main/res/values/strings.xml | 1 + 6 files changed, 85 insertions(+), 26 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt index 368f228c..20ec0453 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderChannels.kt @@ -59,7 +59,7 @@ class ReminderChannels @Inject constructor( channels = plan.channelsToWrite, existing = existing, ) - if (RING_CHANNEL_ID in existingIds) writeRingChannel() + if (RING_CHANNEL_ID in existingIds) ensureRingChannel() val ids = existingIds - plan.staleChannelIds.toSet() + plan.channelsToWrite.map { it.id } lastSync = syncKey(calendars, if (retireLegacyChannel()) ids - LEGACY_REMINDER_CHANNEL_ID else ids) } @@ -91,20 +91,30 @@ class ReminderChannels @Inject constructor( * full-screen intent degrades to. */ private fun ringChannel(): String { - val manager = manager - if (manager.getNotificationChannel(RING_CHANNEL_ID) == null) writeRingChannel() + ensureRingChannel() return RING_CHANNEL_ID } - /** Creates the ring channel, or renames it after a language change. */ - private fun writeRingChannel() { + /** + * Creates the ring channel, or renames it after a language change. Called + * as soon as a calendar is set to ring, so the channel can be checked in + * system settings (and switched on, where a skin starts it off) before the + * first ring. + */ + @Synchronized + fun ensureRingChannel() { + val manager = manager + val name = context.getString(R.string.reminder_ring_channel_name) + val description = context.getString(R.string.reminder_ring_channel_description) + val current = manager.getNotificationChannel(RING_CHANNEL_ID) + if (current != null && current.name?.toString() == name && current.description == description) return manager.createNotificationChannel( NotificationChannel( RING_CHANNEL_ID, - context.getString(R.string.reminder_ring_channel_name), + name, NotificationManager.IMPORTANCE_HIGH, ).apply { - description = context.getString(R.string.reminder_ring_channel_description) + this.description = description setSound(null, null) enableVibration(false) lockscreenVisibility = Notification.VISIBILITY_PUBLIC @@ -118,12 +128,8 @@ class ReminderChannels @Inject constructor( * the sound itself. */ fun canRing(calendarId: Long): Boolean { - val manager = manager - return listOf(reminderChannelId(calendarId), RING_CHANNEL_ID).none { id -> - val channel = manager.getNotificationChannel(id) ?: return@none false - channel.importance == NotificationManager.IMPORTANCE_NONE || - channel.group?.let { manager.getNotificationChannelGroup(it)?.isBlocked } == true - } + val status = status(listOf(calendarId)) + return !status.appBlocked && calendarId !in status.blockedCalendarIds && !status.ringBlocked } private fun calendarChannelFor(calendarId: Long): String? { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt index f4a24547..5d6582e6 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderNotifier.kt @@ -77,7 +77,7 @@ class ReminderNotifier @Inject constructor( */ suspend fun post(alert: ReminderAlert, quiet: Boolean = false, ring: Boolean = true) { if (isSilenced(alert.calendarId)) return - val style = when { + var style = when { quiet -> ReminderAlertStyle.Notification else -> effectiveStyle(alert).let { if (it == ReminderAlertStyle.FullScreenRing && !ring) ReminderAlertStyle.FullScreen else it @@ -85,7 +85,14 @@ class ReminderNotifier @Inject constructor( } // Rung already and handed back to the shade: a catch-up post leaves it there. if (style == ReminderAlertStyle.FullScreenRing && (isShowing(alert) || alerts.isPending(alert))) return - val channelId = channelFor(alert, style) ?: return + val channelId = channelFor(alert, style) + // The ring channel could not be made: still full-screen, sounding once. + ?: if (style == ReminderAlertStyle.FullScreenRing) { + style = ReminderAlertStyle.FullScreen + channelFor(alert, style) ?: return + } else { + return + } val title = displayTitle(alert) val text = contentText(alert) if (style == ReminderAlertStyle.FullScreenRing) { @@ -108,13 +115,15 @@ class ReminderNotifier @Inject constructor( /** Whether a ring for [alert] should go on, now that settings may have changed since it started. */ suspend fun ringVerdict(alert: ReminderAlert): RingVerdict = when { - !settingsPrefs.remindersEnabled.first() || !canPost() || isSilenced(alert.calendarId) -> RingVerdict.Drop + !settingsPrefs.remindersEnabled.first() || !canPost() || isSilenced(alert.calendarId) || + calendarDataSource.isCalendarVisible(alert.calendarId) == null -> RingVerdict.Drop effectiveStyle(alert) != ReminderAlertStyle.FullScreenRing -> RingVerdict.HandBack else -> RingVerdict.Ring } - /** Whether a live ring for [alert] may go on: its notification can still be seen. */ - fun canStillRing(alert: ReminderAlert): Boolean = canPost() && channels.canRing(alert.calendarId) + /** Whether a live ring for [alert] may go on: its notification can still be seen, and its calendar still notifies. */ + suspend fun canStillRing(alert: ReminderAlert): Boolean = + canPost() && channels.canRing(alert.calendarId) && !isSilenced(alert.calendarId) /** The calendar's style, short of ringing where the user blocked its calendar, group or the ring channel. */ private suspend fun effectiveStyle(alert: ReminderAlert): ReminderAlertStyle { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt index 93aaaa91..47244dd3 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/data/reminders/ReminderRingService.kt @@ -172,7 +172,7 @@ class ReminderRingService : Service() { var sounding = false var tick = 0 while (true) { - if (tick++ % VISIBILITY_CHECK_TICKS == 0 && !notifier.canStillRing(alert)) { + if (tick++ % VISIBILITY_CHECK_TICKS == 0 && !stillRings(alert)) { handBack(alert) end() return @@ -191,6 +191,15 @@ class ReminderRingService : Service() { } } + private suspend fun stillRings(alert: ReminderAlert): Boolean = try { + withContext(Dispatchers.IO) { notifier.canStillRing(alert) } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + Log.w(TAG, "Could not re-check the ring for event ${alert.eventId}", e) + true + } + private fun stop(intent: Intent) { val current = alerts.ringing if (current != null && matchFrom(intent).matches(current)) { diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt index 63f8281c..4b359dee 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/NotificationSettings.kt @@ -229,11 +229,19 @@ internal fun NotificationsScreen( val expanded = calendar.id in expandedCalendars val notifying = calendar.id !in state.mutedReminderCalendarIds val blocked = notifying && calendar.id in channelStatus.blockedCalendarIds + val heldBack = fullScreenHeldBack( + style = state.reminderAlertStyles.alertStyleFor(calendar.id), + notifying = notifying, + blocked = blocked, + ringBlocked = channelStatus.ringBlocked, + canFullScreen = canFullScreen, + ) GroupedRow( title = calendar.displayName.orUnnamed(), summary = when { !notifying -> stringResource(R.string.settings_calendar_notifications_off) blocked -> stringResource(R.string.settings_notifications_blocked) + heldBack.any -> stringResource(R.string.settings_full_screen_held_back) else -> null }, position = if (expanded) Position.Top else Position.Alone, @@ -257,11 +265,10 @@ internal fun NotificationsScreen( state = state, notifying = notifying, blocked = blocked, - ringBlocked = channelStatus.ringBlocked, + heldBack = heldBack, onOpenRingSettings = { context.openNotificationSettings(RING_CHANNEL_ID) }, onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) }, onOpenSound = { openCalendarSound(calendar.id) }, - canFullScreen = canFullScreen, onEditAlertStyle = { alertStylePicker = calendar.id }, onEditAlertSound = { alertSoundPicker = calendar.id }, onAllowFullScreen = { context.openFullScreenIntentSettings() }, @@ -410,11 +417,10 @@ private fun CalendarNotificationRows( state: SettingsUiState, notifying: Boolean, blocked: Boolean, - ringBlocked: Boolean, + heldBack: FullScreenHeldBack, onOpenRingSettings: () -> Unit, onSetNotifying: (Boolean) -> Unit, onOpenSound: () -> Unit, - canFullScreen: Boolean, onEditAlertStyle: () -> Unit, onEditAlertSound: () -> Unit, onAllowFullScreen: () -> Unit, @@ -424,8 +430,8 @@ private fun CalendarNotificationRows( val managed = calendar.id in state.managedCalendarIds val takesOverrides = calendar.canModifyContents && !managed val alertStyle = state.reminderAlertStyles.alertStyleFor(calendar.id) - val needsPermission = alertStyle.isFullScreen && !canFullScreen - val ringHeldBack = alertStyle == ReminderAlertStyle.FullScreenRing && ringBlocked && !blocked + val needsPermission = heldBack.permission + val ringHeldBack = heldBack.ring Column { GroupedSwitchRow( title = stringResource(R.string.settings_calendar_notifications), @@ -562,6 +568,25 @@ private fun calendarOverrideSummary( is ReminderOverride.Minutes -> reminderChoiceLabel(choice.minutes) } +/** What keeps a full-screen calendar from alerting as chosen: the missing permission, or the blocked ring channel. */ +private data class FullScreenHeldBack(val permission: Boolean, val ring: Boolean) { + val any: Boolean get() = permission || ring +} + +private fun fullScreenHeldBack( + style: ReminderAlertStyle, + notifying: Boolean, + blocked: Boolean, + ringBlocked: Boolean, + canFullScreen: Boolean, +): FullScreenHeldBack { + val live = notifying && !blocked + return FullScreenHeldBack( + permission = live && style.isFullScreen && !canFullScreen, + ring = live && style == ReminderAlertStyle.FullScreenRing && ringBlocked, + ) +} + @Composable private fun alertStyleLabel(style: ReminderAlertStyle): String = stringResource( if (style.isFullScreen) R.string.settings_alert_style_full_screen else R.string.settings_alert_style_notification, diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt index 80b553af..4aaaa3a0 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/settings/SettingsViewModel.kt @@ -391,6 +391,11 @@ class SettingsViewModel @Inject constructor( fun setCalendarAlertStyle(calendarId: Long, style: ReminderAlertStyle) { viewModelScope.launch { prefs.setCalendarAlertStyle(calendarId, style) + // Up front, so it can be checked in system settings before the first ring. + if (style == ReminderAlertStyle.FullScreenRing) { + onChannels { ensureRingChannel() } + refreshChannelStatus(state.value.reminderCalendars.map { it.id }) + } // A ring for it goes quiet but stays in the shade. if (style != ReminderAlertStyle.FullScreenRing) { reminderNotifier.stopRing(RingMatch.Calendar(calendarId), handBack = true) @@ -427,7 +432,11 @@ class SettingsViewModel @Inject constructor( /** Create the per-calendar channels before showing the app's channel list, even with reminders off. */ suspend fun syncReminderChannels() { - onChannels { sync() } + val ringing = state.value.reminderAlertStyles.containsValue(ReminderAlertStyle.FullScreenRing) + onChannels { + sync() + if (ringing) ensureRingChannel() + } } private suspend fun onChannels(block: ReminderChannels.() -> T): T? = withContext(io) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 4e433d57..44e4c6ff 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -755,6 +755,7 @@ Ring until dismissed Your alarm sound and vibration, like an alarm, also in Do Not Disturb when alarms may sound Ringing reminders use your alarm sound. This sets the sound of the ones handed back to the shade. + Full-screen alerts held back Blocked in system settings, so this calendar\'s reminders only sound once — tap to allow Allow full-screen alerts Android blocks Calendula\'s full-screen alerts, so they only pop up as notifications. Tap to allow them. From ed72920da17b8b4b5d3d4a11795eb46546f84edb Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Mon, 16 Nov 2026 19:31:48 +0100 Subject: [PATCH 11/11] fix(#171): stack the alert's large buttons so their labels fit --- .../ui/reminders/ReminderAlertScreen.kt | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt index dde55087..6cd8de1c 100644 --- a/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt +++ b/app/src/main/java/de/jeanlucmakiola/calendula/ui/reminders/ReminderAlertScreen.kt @@ -121,23 +121,23 @@ internal fun ReminderAlertScreen( } } Spacer(Modifier.size(24.dp)) - Row( + Column( modifier = Modifier.widthIn(max = 480.dp).fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), ) { - AlertButton( - label = stringResource(R.string.reminder_action_snooze), - icon = Icons.Outlined.Snooze, - tonal = true, - onClick = onSnooze, - modifier = Modifier.weight(1f), - ) AlertButton( label = stringResource(R.string.reminder_action_dismiss), icon = Icons.Rounded.Close, tonal = false, onClick = onDismiss, - modifier = Modifier.weight(1f), + modifier = Modifier.fillMaxWidth(), + ) + AlertButton( + label = stringResource(R.string.reminder_action_snooze), + icon = Icons.Outlined.Snooze, + tonal = true, + onClick = onSnooze, + modifier = Modifier.fillMaxWidth(), ) } }