From 6cf6a6fdbff1d7933e791409570c0e0aff537aa8 Mon Sep 17 00:00:00 2001 From: Jean-Luc Makiola Date: Fri, 13 Nov 2026 17:33:26 +0100 Subject: [PATCH] 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