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

This commit is contained in:
makiolaj committed 2026-11-13 18:06:17 +01:00
1 parent 014d31f9b9
commit 0b6cdf992e
3 files changed
+71 -42

No files matched your search

@@ -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<Long, ReminderAlert>()
/** 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<Long>(
extraBufferCapacity = 8,
@@ -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. */
@@ -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))
}
}