fix(#518): review round 2 — late channel resolve, failure feedback, no sound flash, safer picks

This commit is contained in:
makiolaj committed 2026-11-14 04:06:32 +01:00
1 parent 18b9f19a61
commit 661300728a
6 files changed
+89 -51

No files matched your search

@@ -54,7 +54,7 @@ class ReminderChannels @Inject constructor(
val manager = manager
val existing = manager.notificationChannels
val existingIds = existing.mapTo(HashSet()) { it.id }
val versions = currentVersions(existingIds)
val versions = currentVersions(existingIds).also { knownVersions = it }
if (syncKey(calendars, existingIds, versions) == lastSync && LEGACY_REMINDER_CHANNEL_ID !in existingIds) return
val groups = manager.notificationChannelGroups
val plan = plan(calendars, existing, groups.map { it.id }, versions, showingChannelIds())
@@ -83,6 +83,14 @@ class ReminderChannels @Inject constructor(
versions,
)
/**
* The current versions last resolved under the lock ([sync], [channelFor]).
* Only [recreate], under the same lock, moves a calendar higher and updates
* it, so a hit whose channel still exists is current.
*/
@Volatile
private var knownVersions: Map<Long, Int> = emptyMap()
private fun currentVersions(existingChannelIds: Collection<String>): Map<Long, Int> =
currentReminderChannelVersions(existingChannelIds, runBlocking { settingsPrefs.reminderChannelVersions.first() })
@@ -104,8 +112,12 @@ class ReminderChannels @Inject constructor(
@Synchronized
fun channelFor(calendarId: Long): String? {
val manager = manager
knownVersions[calendarId]?.let { version ->
val known = reminderChannelId(calendarId, version)
if (manager.getNotificationChannel(known) != null) return known
}
val existing = manager.notificationChannels
val versions = currentVersions(existing.map { it.id })
val versions = currentVersions(existing.map { it.id }).also { knownVersions = it }
val id = reminderChannelId(calendarId, versions[calendarId] ?: 0)
if (existing.any { it.id == id }) return id
val calendars = try {
@@ -163,40 +175,49 @@ class ReminderChannels @Inject constructor(
* Give [calendarIds]' reminders [sound] (null = silent). A channel's sound is
* fixed once created, so each moves to a new channel version carrying over
* everything else, and the old one retires (#518). Calendars without a
* channel are skipped unless [createMissing].
* channel are skipped unless [createMissing]. Returns whether every move
* went through.
*/
suspend fun setSound(calendarIds: Collection<Long>, sound: Uri?, createMissing: Boolean) {
suspend fun setSound(calendarIds: Collection<Long>, sound: Uri?, createMissing: Boolean): Boolean {
if (createMissing) calendarIds.forEach(::channelFor)
val existingIds = manager.notificationChannels.mapTo(HashSet()) { it.id }
val current = currentVersions(existingIds)
val floors = calendarIds
.filter { reminderChannelId(it, current[it] ?: 0) in existingIds }
.associateWith { (current[it] ?: 0) + 1 }
if (floors.isEmpty()) return
recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound)
if (floors.isEmpty()) return true
return recreate(settingsPrefs.reserveReminderChannelVersions(floors), sound)
}
/** Create each calendar's [versions] from its current channel, then retire the old one. */
@Synchronized
private fun recreate(versions: Map<Long, Int>, sound: Uri?) {
private fun recreate(versions: Map<Long, Int>, sound: Uri?): Boolean {
val manager = manager
val byId = manager.notificationChannels.associateBy { it.id }
val current = currentReminderChannelVersions(byId.keys, emptyMap())
val showing = showingChannelIds()
var allApplied = true
versions.forEach { (calendarId, version) ->
val from = current[calendarId]?.takeIf { it < version } ?: return@forEach
val old = byId[reminderChannelId(calendarId, from)] ?: return@forEach
manager.createNotificationChannel(
NotificationChannel(reminderChannelId(calendarId, version), old.name, old.importance).apply {
description = old.description
old.group?.let { group = it }
inheritFrom(old)
setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES)
},
)
if (old.id !in showing) manager.deleteNotificationChannel(old.id)
try {
manager.createNotificationChannel(
NotificationChannel(reminderChannelId(calendarId, version), old.name, old.importance).apply {
description = old.description
old.group?.let { group = it }
inheritFrom(old)
setSound(sound, old.audioAttributes ?: DEFAULT_AUDIO_ATTRIBUTES)
},
)
knownVersions = knownVersions + (calendarId to version)
if (old.id !in showing) manager.deleteNotificationChannel(old.id)
} catch (e: RuntimeException) {
Log.w(TAG, "Could not move calendar $calendarId to a new sound", e)
allApplied = false
}
}
lastSync = null
return allApplied
}
private fun plan(
@@ -246,9 +267,10 @@ class ReminderChannels @Inject constructor(
}
/**
* Carry a channel's sound, vibration, lights, badge and lock-screen choice
* over to a new one: the legacy channel to a per-calendar one on upgrade, or
* a calendar's channel to its next version (#518).
* Carry a channel's sound, vibration, lights and badge over to a new one: the
* legacy channel to a per-calendar one on upgrade, or a calendar's channel to
* its next version (#518). Lock-screen visibility and a DND override can't
* follow: the system resets both on channels an app creates.
*/
private fun NotificationChannel.inheritFrom(template: NotificationChannel) {
setSound(template.sound, template.audioAttributes)
@@ -258,8 +280,6 @@ class ReminderChannels @Inject constructor(
enableLights(template.shouldShowLights())
lightColor = template.lightColor
setShowBadge(template.canShowBadge())
// The system only keeps a private or secret choice; "public" resets to its default.
lockscreenVisibility = template.lockscreenVisibility
// Only honoured with Do Not Disturb access, so usually left to the user.
setBypassDnd(template.canBypassDnd())
}
@@ -272,12 +292,7 @@ class ReminderChannels @Inject constructor(
private fun retireLegacyChannel(): Boolean {
val manager = manager
if (manager.getNotificationChannel(LEGACY_REMINDER_CHANNEL_ID) == null) return true
val showing = runCatching {
manager.activeNotifications.any { it.notification.channelId == LEGACY_REMINDER_CHANNEL_ID }
}.getOrElse { e ->
Log.w(TAG, "Could not read active notifications", e)
true
}
val showing = LEGACY_REMINDER_CHANNEL_ID in showingChannelIds()
if (!showing) manager.deleteNotificationChannel(LEGACY_REMINDER_CHANNEL_ID)
return !showing
}
@@ -293,7 +308,7 @@ class ReminderChannels @Inject constructor(
const val TAG = "ReminderChannels"
val DEFAULT_AUDIO_ATTRIBUTES: AudioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
}
@@ -65,15 +65,6 @@ class ReminderNotifier @Inject constructor(
/** Post [alert], unless its calendar is silenced or gone. */
suspend fun post(alert: ReminderAlert) {
if (isSilenced(alert.calendarId)) return
val channelId = try {
channels.channelFor(alert.calendarId) ?: run {
Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone")
return
}
} catch (e: Exception) {
Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e)
return
}
val title = displayTitle(alert)
val is24Hour = settingsPrefs.timeFormat.first()
.is24Hour(android.text.format.DateFormat.is24HourFormat(context))
@@ -96,6 +87,16 @@ class ReminderNotifier @Inject constructor(
yesterdayLabel = context.getString(R.string.reminder_day_yesterday),
)
val text = listOfNotNull(time, alert.location).joinToString(" · ")
// Resolved last, so a sound picked meanwhile (#518) can't retire it before notify.
val channelId = try {
channels.channelFor(alert.calendarId) ?: run {
Log.i(TAG, "Dropped the reminder of event ${alert.eventId}: calendar ${alert.calendarId} is gone")
return
}
} catch (e: Exception) {
Log.w(TAG, "No channel for the reminder of event ${alert.eventId}", e)
return
}
val notification = NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
@@ -8,6 +8,7 @@ import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import android.provider.Settings.System.DEFAULT_NOTIFICATION_URI
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.AnimatedVisibility
@@ -27,6 +28,7 @@ import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
@@ -122,7 +124,14 @@ internal fun NotificationsScreen(
context.openNotificationSettings()
}
}
val sounds by viewModel.channelSounds.collectAsStateWithLifecycle()
val loadedSounds by viewModel.channelSounds.collectAsStateWithLifecycle()
val sounds = loadedSounds.orEmpty()
val soundFailedMessage = stringResource(R.string.settings_notification_sound_failed)
LaunchedEffect(Unit) {
viewModel.soundFailed.collect {
Toast.makeText(context, soundFailedMessage, Toast.LENGTH_LONG).show()
}
}
// ALL_CALENDARS, a calendar id, or null when no pick is pending.
var soundTarget by rememberSaveable { mutableStateOf<Long?>(null) }
val soundPicker = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
@@ -136,7 +145,8 @@ internal fun NotificationsScreen(
}
}
val pickSoundTitle = stringResource(R.string.settings_notification_sound)
val pickSound: (Long) -> Unit = { target ->
val pickSound: (Long) -> Unit = pick@{ target ->
if (soundTarget != null) return@pick
val current = if (target == ALL_CALENDARS) {
(sharedSound(sounds, calendarIds) as? SharedSound.Same)?.sound
} else {
@@ -179,7 +189,7 @@ internal fun NotificationsScreen(
if (calendarIds.isNotEmpty()) {
GroupedRow(
title = stringResource(R.string.settings_notification_sound),
summary = globalSoundLabel(sounds, calendarIds),
summary = loadedSounds?.let { globalSoundLabel(it, calendarIds) },
position = Position.Middle,
onClick = { pickSound(ALL_CALENDARS) },
)
@@ -293,7 +303,7 @@ internal fun NotificationsScreen(
state = state,
notifying = notifying,
blocked = blocked,
soundLabel = soundLabel(sounds[calendar.id]),
soundLabel = loadedSounds?.let { soundLabel(it[calendar.id]) },
onSetNotifying = { viewModel.setCalendarRemindersEnabled(calendar.id, it) },
onPickSound = { pickSound(calendar.id) },
onOpenSettings = { openCalendarSettings(calendar.id) },
@@ -397,7 +407,7 @@ private fun CalendarNotificationRows(
state: SettingsUiState,
notifying: Boolean,
blocked: Boolean,
soundLabel: String,
soundLabel: String?,
onSetNotifying: (Boolean) -> Unit,
onPickSound: () -> Unit,
onOpenSettings: () -> Unit,
@@ -53,6 +53,7 @@ import de.jeanlucmakiola.calendula.ui.theme.FONT_CUSTOM_TOKEN
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
@@ -390,10 +391,15 @@ class SettingsViewModel @Inject constructor(
private var channelStatusJob: Job? = null
private val _channelSounds = MutableStateFlow<Map<Long, ReminderSound>>(emptyMap())
private val _channelSounds = MutableStateFlow<Map<Long, ReminderSound>?>(null)
/** Each calendar's reminder sound (#518); a calendar without a channel yet is absent. */
val channelSounds: StateFlow<Map<Long, ReminderSound>> = _channelSounds.asStateFlow()
/** Each calendar's reminder sound (#518), null until first read; a calendar without a channel yet is absent. */
val channelSounds: StateFlow<Map<Long, ReminderSound>?> = _channelSounds.asStateFlow()
private val _soundFailed = MutableSharedFlow<Unit>(extraBufferCapacity = 1)
/** Emits when a picked sound couldn't be applied to every calendar. */
val soundFailed: SharedFlow<Unit> = _soundFailed
fun refreshChannelStatus(calendarIds: Collection<Long>) {
channelStatusJob?.cancel()
@@ -416,21 +422,26 @@ class SettingsViewModel @Inject constructor(
* that only get a channel when something posts are left alone.
*/
fun setReminderSoundForAll(sound: Uri?) = applySound {
sync()
try {
sync()
} catch (e: Exception) {
Log.w("SettingsViewModel", "Channel sync before a sound pick failed", e)
}
setSound(visibleCalendars.first().map { it.id }, sound, createMissing = false)
}
private fun applySound(block: suspend ReminderChannels.() -> Unit) {
/** Runs to completion even if the screen closes meanwhile, so a pick is never half-applied. */
private fun applySound(block: suspend ReminderChannels.() -> Boolean) {
viewModelScope.launch {
withContext(io) {
val applied = withContext(io + NonCancellable) {
try {
reminderChannels.block()
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w("SettingsViewModel", "Could not set the reminder sound", e)
false
}
}
if (!applied) _soundFailed.tryEmit(Unit)
refreshChannelStatus(visibleCalendars.first().map { it.id })
}
}
+1
View File
@@ -741,6 +741,7 @@
<!-- %1$s is the name of the device's default notification sound. -->
<string name="settings_notification_sound_default_named">Default (%1$s)</string>
<string name="settings_notification_sound_custom">Custom sound</string>
<string name="settings_notification_sound_failed">Couldn\'t change the sound for every calendar</string>
<string name="settings_notification_sound_mixed">Differs per calendar</string>
<string name="settings_notification_more">More notification settings</string>
<string name="settings_notification_sound_hint">Vibration, pop-ups and more for each calendar, in system settings</string>