Modern Apps git

← Modern-Apps.git

clock: always cancel the ringing alarm notification (#571)

Commit
10b97dad6e804e313ad58102fb8e31d38c64c63e
Author
vayun-mathur <[email protected]>
When
2026-09-07 14:19 UTC (2 months ago)
Parents
f716d1a

Diff

clock/src/main/java/com/vayunmathur/clock/platform/AlarmActivity.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmActivity.kt b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmActivity.ktindex 805f190c9c..a07c3d20a4 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmActivity.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmActivity.kt@@ -48,14 +48,14 @@ class AlarmActivity : ComponentActivity() {     private fun dismissAlarm() {         stopService(Intent(this, AlarmSoundService::class.java))         val nm = getSystemService(NotificationManager::class.java)-        nm.cancel(alarmId.toInt()); finish()+        nm.cancel(ALARM_RING_NOTIFICATION_ID); finish()     }      private fun snoozeAlarm() {         stopService(Intent(this, AlarmSoundService::class.java))         // The ring notification is insistent, so it keeps sounding until cancelled. Snoozing         // used to leave it posted, which only went unnoticed while the service owned the sound.-        getSystemService(NotificationManager::class.java).cancel(alarmId.toInt())+        getSystemService(NotificationManager::class.java).cancel(ALARM_RING_NOTIFICATION_ID)         val snoozeTime = Clock.System.now().plus(snoozeMinutes.minutes)         val triggerMillis = snoozeTime.toEpochMilliseconds()         val intent = Intent(this, AlarmReceiver::class.java).apply { putExtra("ALARM_ID", alarmId); putExtra("IS_SNOOZE", true) }
clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.ktindex e689a6ea5f..3ab496a0e7 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.kt@@ -47,6 +47,9 @@ class AlarmReceiver : BroadcastReceiver() {             .setCategory(NotificationCompat.CATEGORY_ALARM)             // This is the key: it launches the activity automatically if the phone is locked             .setFullScreenIntent(pendingIntent, true)+            // Without a content intent, tapping the notification does nothing and autoCancel+            // never fires, so the shade offers no way to stop the ring but a swipe.+            .setContentIntent(pendingIntent)             .setAutoCancel(true)             // Backstop: an insistent notification rings forever, so bound it in case every             // dismiss path is missed (process killed before the UI ever appeared, say).@@ -77,7 +80,7 @@ class AlarmReceiver : BroadcastReceiver() {             Log.w(TAG, "Alarm $alarmId: USE_FULL_SCREEN_INTENT not granted; ringing UI may not appear")         }         notificationManager.notify(-            alarmId.toInt(),+            ALARM_RING_NOTIFICATION_ID,             builder.build().apply { flags = flags or Notification.FLAG_INSISTENT },         ) 
clock/src/main/java/com/vayunmathur/clock/platform/NotificationUtils.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/NotificationUtils.kt b/clock/src/main/java/com/vayunmathur/clock/platform/NotificationUtils.ktindex 8778ad8e44..a1ff0b1c59 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/NotificationUtils.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/NotificationUtils.kt@@ -31,6 +31,20 @@ const val ALARM_CHANNEL_ID = "alarm_channel_v2"  */ const val ALARM_RING_CHANNEL_ID = "alarm_ring_channel" +/**+ * The one and only id the insistent ring notification is ever posted under.+ *+ * It is deliberately not per-alarm. An insistent notification rings until it is cancelled, so+ * every cancel site has to be able to name it without knowing which alarm posted it - which+ * AlarmActivity cannot, being `singleInstance` and holding whichever id it was first created+ * with. One id also means a second alarm replaces the first rather than adding a second thing+ * that rings, so at most one can ever be outstanding.+ *+ * Kept well clear of the row-id range: timer notifications are posted under `timer.id.hashCode()`,+ * which for a Room row id is just the id, so anything small eventually collides with one.+ */+const val ALARM_RING_NOTIFICATION_ID = 100_002+ private const val LEGACY_ALARM_CHANNEL_ID = "ALARM_CHANNEL_ID"  fun createNotificationChannels(context: Context) {
clock/src/main/java/com/vayunmathur/clock/service/AlarmSoundService.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/service/AlarmSoundService.kt b/clock/src/main/java/com/vayunmathur/clock/service/AlarmSoundService.ktindex d52f5e83bb..47b3709271 100644--- a/clock/src/main/java/com/vayunmathur/clock/service/AlarmSoundService.kt+++ b/clock/src/main/java/com/vayunmathur/clock/service/AlarmSoundService.kt@@ -16,6 +16,7 @@ import androidx.core.app.NotificationCompat import androidx.core.net.toUri import com.vayunmathur.clock.R import com.vayunmathur.clock.platform.ALARM_CHANNEL_ID+import com.vayunmathur.clock.platform.ALARM_RING_NOTIFICATION_ID import com.vayunmathur.clock.platform.createAlarmChannel import com.vayunmathur.clock.data.ClockRepository import com.vayunmathur.library.ui.RINGTONE_SILENT@@ -31,6 +32,14 @@ class AlarmSoundService : Service() {     private var mediaPlayer: MediaPlayer? = null     private var vibrator: Vibrator? = null     private var started = false++    /** Whether the MediaPlayer is actually producing sound, so the ring notification is spare. */+    @Volatile+    private var sounding = false++    @Volatile+    private var destroyed = false+     private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)      override fun onCreate() {@@ -61,54 +70,77 @@ class AlarmSoundService : Service() {     override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {         val alarmId = intent?.getLongExtra("ALARM_ID", -1L) ?: -1L -        // We are alive and foreground, so take the ring off the system before doing anything-        // slow: the insistent notification and the MediaPlayer must not overlap for longer than-        // this handover.-        if (alarmId != -1L) {-            getSystemService(NotificationManager::class.java).cancel(alarmId.toInt())+        if (started) {+            // A second alarm has fired and posted its own ring notification over the first.+            // We are already the ringer, so take it back off the system at once; if we are not+            // sounding yet, the launch below is still on its way to doing so.+            if (sounding) cancelRingNotification()+            return START_STICKY         }+        started = true -        // Now handle the hardware, using this alarm's per-alarm settings.-        if (!started) {-            started = true-            scope.launch {-                val alarm = if (alarmId != -1L) {-                    runCatching {-                        ClockRepository.get(applicationContext).getAlarm(alarmId)-                    }.getOrNull()-                } else null--                val ringtoneUri = alarm?.ringtoneUri-                val vibrate = alarm?.vibrate ?: true-                val gradualSeconds = alarm?.gradualVolumeSeconds ?: 0--                // setDataSource()/prepare() are blocking; run them on the IO-                // dispatcher (this coroutine) instead of the main thread.-                //-                // Vibration comes first: a stored ringtone can be a content:// URI owned by-                // another app, and one that no longer resolves used to throw out of playAlarm-                // and take the vibration down with it.-                if (vibrate) {-                    withContext(Dispatchers.Main) { startVibration() }-                }-                if (ringtoneUri != RINGTONE_SILENT) {-                    runCatching { playAlarm(resolveRingtone(ringtoneUri), gradualSeconds) }-                        .onFailure { failure ->-                            Log.e(TAG, "Alarm $alarmId: ringtone $ringtoneUri failed to play", failure)-                            releasePlayer()-                            runCatching { playAlarm(resolveRingtone(null), gradualSeconds) }-                                .onFailure { fallbackFailure ->-                                    Log.e(TAG, "Alarm $alarmId: default ringtone failed too", fallbackFailure)-                                    releasePlayer()-                                }-                        }-                }+        scope.launch {+            val alarm = if (alarmId != -1L) {+                runCatching {+                    ClockRepository.get(applicationContext).getAlarm(alarmId)+                }.getOrNull()+            } else null++            val ringtoneUri = alarm?.ringtoneUri+            val vibrate = alarm?.vibrate ?: true+            val gradualSeconds = alarm?.gradualVolumeSeconds ?: 0++            // setDataSource()/prepare() are blocking; run them on the IO+            // dispatcher (this coroutine) instead of the main thread.+            //+            // Vibration comes first: a stored ringtone can be a content:// URI owned by+            // another app, and one that no longer resolves used to throw out of playAlarm+            // and take the vibration down with it.+            if (vibrate) {+                withContext(Dispatchers.Main) { startVibration() }+            }++            val silent = ringtoneUri == RINGTONE_SILENT+            sounding = !silent && (+                tryPlay(resolveRingtone(ringtoneUri), gradualSeconds, alarmId) ||+                    tryPlay(resolveRingtone(null), gradualSeconds, alarmId)+                )++            // Only now hand the ring over. Cancelling on entry to onStartCommand instead would+            // drop the safety net during the database read and prepare() above - the slow part,+            // on exactly the hardware this is meant to fix - and drop it permanently if neither+            // ringtone plays, which is the one case it exists for.+            if (silent || sounding) {+                cancelRingNotification()+            } else {+                Log.e(TAG, "Alarm $alarmId: no ringtone played; leaving the ring notification up")             }         }          return START_STICKY     } +    private fun tryPlay(uri: Uri?, gradualSeconds: Int, alarmId: Long): Boolean {+        val playing = runCatching { playAlarm(uri, gradualSeconds) }+            .onFailure {+                Log.e(TAG, "Alarm $alarmId: ringtone $uri failed to play", it)+                releasePlayer()+            }+            .getOrDefault(false)+        // prepare() blocks and is not cancellable, so onDestroy can have come and gone while we+        // were inside it - releasing a player that did not exist yet and leaving this one with+        // nothing left alive to stop it.+        if (playing && destroyed) {+            releasePlayer()+            return false+        }+        return playing+    }++    private fun cancelRingNotification() {+        getSystemService(NotificationManager::class.java).cancel(ALARM_RING_NOTIFICATION_ID)+    }+     private fun resolveRingtone(uriString: String?): Uri? = when (uriString) {         null -> RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)             ?: RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)@@ -116,8 +148,8 @@ class AlarmSoundService : Service() {         else -> runCatching { uriString.toUri() }.getOrNull()     } -    private fun playAlarm(alarmUri: Uri?, gradualSeconds: Int) {-        alarmUri ?: return+    private fun playAlarm(alarmUri: Uri?, gradualSeconds: Int): Boolean {+        alarmUri ?: return false         mediaPlayer = MediaPlayer().apply {             setDataSource(applicationContext, alarmUri)             setAudioAttributes(@@ -132,6 +164,7 @@ class AlarmSoundService : Service() {             start()         }         if (gradualSeconds > 0) rampVolume(gradualSeconds)+        return true     }      private fun releasePlayer() {@@ -161,6 +194,7 @@ class AlarmSoundService : Service() {     }      override fun onDestroy() {+        destroyed = true         scope.cancel()         mediaPlayer?.stop()         mediaPlayer?.release()