Modern Apps git

← Modern-Apps.git

clock: fix alarm ringing, fullscreen intent, and snooze timing

Commit
270805b7db19958526142a182a2358e08551905a
Author
vayun-mathur <[email protected]>
When
2026-10-23 03:23 UTC (1 month ago)
Parents
5527857

Diff

clock/src/main/java/com/vayunmathur/clock/MainActivity.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/MainActivity.kt b/clock/src/main/java/com/vayunmathur/clock/MainActivity.ktindex 4ceb6462dc..6d9ddf778a 100644--- a/clock/src/main/java/com/vayunmathur/clock/MainActivity.kt+++ b/clock/src/main/java/com/vayunmathur/clock/MainActivity.kt@@ -1,16 +1,40 @@ package com.vayunmathur.clock  import androidx.activity.viewModels+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwner import com.vayunmathur.clock.data.ClockRepository import com.vayunmathur.clock.platform.ClockViewModel import com.vayunmathur.clock.platform.ClockViewModelFactory import com.vayunmathur.clock.platform.createNotificationChannels import com.vayunmathur.library.ui.AppPermissionsGate import com.vayunmathur.library.ui.AppPermissionsSpec+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.IconAlarm+import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.MaActivity import com.vayunmathur.library.ui.PermissionRequirement+import com.vayunmathur.library.ui.SpecialAccess+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.util.DataStoreUtils  class MainActivity : MaActivity() {@@ -38,7 +62,45 @@ class MainActivity : MaActivity() {                 )             )         ) {-            Navigation(ds, clockViewModel, initialRoute)+            Column {+                FullscreenRevokedBanner(modifier = Modifier.fillMaxWidth())+                Navigation(ds, clockViewModel, initialRoute)+            }         }     } }++/**+ * The gate above only runs at first launch; the full-screen permission is a+ * toggle the user can revoke at any time afterwards, silently degrading every+ * future alarm to a heads-up. Re-check on every resume and say so in-app,+ * with a one-tap path back to the settings page.+ */+@Composable+private fun FullscreenRevokedBanner(modifier: Modifier = Modifier) {+    val context = LocalContext.current+    var resumeEpoch by remember { mutableIntStateOf(0) }+    val lifecycleOwner = LocalLifecycleOwner.current+    DisposableEffect(lifecycleOwner) {+        val observer = LifecycleEventObserver { _, event ->+            if (event == Lifecycle.Event.ON_RESUME) resumeEpoch+++        }+        lifecycleOwner.lifecycle.addObserver(observer)+        onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }+    }+    val revoked = remember(resumeEpoch) {+        !SpecialAccess.hasFullScreenIntent(context)+    }+    if (!revoked) return+    Card(modifier = modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {+        ListItem(+            headlineContent = { Text(stringResource(R.string.alarm_fullscreen_revoked)) },+            leadingContent = { IconAlarm() },+            trailingContent = {+                TextButton(onClick = { SpecialAccess.requestFullScreenIntent(context) }) {+                    Text(stringResource(R.string.action_open_settings))+                }+            },+        )+    }+}
clock/src/main/java/com/vayunmathur/clock/data/ClockDatabase.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/data/ClockDatabase.kt b/clock/src/main/java/com/vayunmathur/clock/data/ClockDatabase.ktindex 137ddd23c3..9c00bdf06b 100644--- a/clock/src/main/java/com/vayunmathur/clock/data/ClockDatabase.kt+++ b/clock/src/main/java/com/vayunmathur/clock/data/ClockDatabase.kt@@ -50,6 +50,12 @@ data class Alarm(     var vibrate: Boolean = true,     var snoozeMinutes: Int = 5,     var gradualVolumeSeconds: Int = 0, // 0 = play at full volume immediately+    /**+     * When a snoozed ring is due. Set when the user snoozes, cleared when that+     * snooze fires (or is superseded); the snooze PendingIntent lives only in+     * AlarmManager, so without this a reboot would silently drop it.+     */+    var snoozedUntil: Instant? = null,     @PrimaryKey(autoGenerate = true)     override var id: Long = 0, ): DatabaseItem@@ -91,7 +97,7 @@ interface AlarmDao { }  @ColumnTypeConverters(DefaultConverters::class)-@Database(entities = [Timer::class, Alarm::class], version = 2, exportSchema = false)+@Database(entities = [Timer::class, Alarm::class], version = 3, exportSchema = false) abstract class ClockDatabase: RoomDatabase() {     abstract fun timerDao(): TimerDao     abstract fun alarmDao(): AlarmDao@@ -104,6 +110,9 @@ abstract class ClockDatabase: RoomDatabase() {                 it.execSQL("ALTER TABLE Alarm ADD COLUMN snoozeMinutes INTEGER NOT NULL DEFAULT 5")                 it.execSQL("ALTER TABLE Alarm ADD COLUMN gradualVolumeSeconds INTEGER NOT NULL DEFAULT 0")             },+            Migration(2, 3) {+                it.execSQL("ALTER TABLE Alarm ADD COLUMN snoozedUntil INTEGER")+            },         )     } }
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 5e286118ff..ff40d3209c 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmActivity.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmActivity.kt@@ -1,56 +1,43 @@ package com.vayunmathur.clock.platform-import android.app.AlarmManager-import android.app.KeyguardManager import android.app.NotificationManager-import android.app.PendingIntent import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.lifecycle.lifecycleScope import com.vayunmathur.clock.R+import com.vayunmathur.clock.data.Alarm import com.vayunmathur.clock.data.ClockRepository import com.vayunmathur.clock.ui.components.AlarmRingingScreen import com.vayunmathur.clock.ui.components.formatAlarmTime import com.vayunmathur.clock.service.AlarmSoundService+import com.vayunmathur.library.log.Log import com.vayunmathur.library.ui.DynamicTheme-import kotlin.time.Clock-import kotlin.time.Duration.Companion.minutes import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch import kotlinx.coroutines.withContext  class AlarmActivity : ComponentActivity() {     private var alarmId: Long = -1L-    private var snoozeMinutes: Int = 5-    private var gradualSeconds: Int = 0-    private var alarmLabel: String = ""+    private var alarm: Alarm? by mutableStateOf(null)      override fun onCreate(savedInstanceState: Bundle?) {         setShowWhenLocked(true); setTurnScreenOn(true); super.onCreate(savedInstanceState)         alarmId = intent.getLongExtra("ALARM_ID", -1L)-        val km = getSystemService(KEYGUARD_SERVICE) as KeyguardManager-        km.requestDismissKeyguard(this, null)-        val repository = ClockRepository.get(applicationContext)+        loadAlarm(intent)         setContent {-            val alarm by androidx.compose.runtime.produceState<com.vayunmathur.clock.data.Alarm?>(initialValue = null) {-                value = withContext(Dispatchers.IO) { repository.getAlarm(alarmId) }-            }-            androidx.compose.runtime.LaunchedEffect(alarm) {-                alarm?.let {-                    snoozeMinutes = it.snoozeMinutes-                    gradualSeconds = it.gradualVolumeSeconds-                    alarmLabel = it.name-                }-            }             DynamicTheme {                 AlarmRingingScreen(                     alarmTime = alarm?.let { formatAlarmTime(this@AlarmActivity, it.time) } ?: "--:--",                     alarmName = alarm?.name ?: getString(R.string.label_alarm),-                    // Read off the loaded alarm, not the field: the field is only assigned in-                    // the LaunchedEffect below (after composition), so passing it would still-                    // show the default 5 on first draw. The field stays for snoozeAlarm(),-                    // which reads it from a click handler long after load.-                    snoozeMinutes = alarm?.snoozeMinutes ?: snoozeMinutes,+                    // The alarm is loaded async; read it off state (not a field+                    // assigned in a LaunchedEffect after composition) so the first+                    // draw already shows the real value once loaded.+                    snoozeMinutes = alarm?.snoozeMinutes ?: 5,+                    snoozeEnabled = alarm != null,                     onDismiss = { dismissAlarm() },                     onSnooze = { snoozeAlarm() }                 )@@ -58,36 +45,81 @@ class AlarmActivity : ComponentActivity() {         }     } +    /**+     * singleInstance reuses this activity for a second alarm fired while the+     * first is still showing; without this the dismiss/snooze buttons would+     * keep acting on the stale id and the UI would show the wrong alarm.+     */+    override fun onNewIntent(intent: Intent) {+        super.onNewIntent(intent)+        setIntent(intent)+        alarmId = intent.getLongExtra("ALARM_ID", -1L)+        loadAlarm(intent)+    }++    private fun loadAlarm(intent: Intent) {+        val id = intent.getLongExtra("ALARM_ID", -1L)+        if (id == -1L) {+            Log.error(TAG, "Ringing activity started without an alarm id")+            finish()+            return+        }+        alarm = null+        lifecycleScope.launch(Dispatchers.IO) {+            runCatching { ClockRepository.get(applicationContext).getAlarm(id) }+                .onSuccess { loaded -> withContext(Dispatchers.Main) { alarm = loaded } }+                .onFailure {+                    Log.error(TAG, "Alarm $id: could not load ringing alarm", it)+                    withContext(Dispatchers.Main) { finish() }+                }+        }+    }+     private fun dismissAlarm() {+        val ringing = alarm         stopService(Intent(this, AlarmSoundService::class.java))         val nm = getSystemService(NotificationManager::class.java)         nm.cancel(ALARM_RING_NOTIFICATION_ID); finish()+        if (ringing != null) {+            // Dismissing also drops any pending snooze: the user stopped the alarm,+            // they did not ask to be woken again in five minutes.+            val ctx = this+            lifecycleScope.launch(Dispatchers.IO) {+                runCatching {+                    AlarmScheduler.clearSnooze(ctx, ClockRepository.get(ctx), ringing)+                }.onFailure {+                    Log.error(TAG, "Alarm ${ringing.id}: could not clear snooze on dismiss", it)+                }+            }+        }     }      private fun snoozeAlarm() {+        // Snooze is disabled until the alarm loads (snoozeEnabled above), but a+        // stale click could still land here; guard rather than schedule garbage.+        val ringing = alarm ?: return+        // Stop the sound first so the snooze tap never overlaps the old ring, and+        // clear the insistent notification the receiver posted: it keeps sounding+        // on the system side after the service dies.         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(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)-            // Snooze builds its own intent rather than going through AlarmScheduler, so it has-            // to carry this itself or the snoozed alarm would ring on the wrong channel.-            putExtra(AlarmScheduler.EXTRA_GRADUAL_SECONDS, gradualSeconds)-            putExtra(AlarmScheduler.EXTRA_LABEL, alarmLabel)+        val ctx = this+        lifecycleScope.launch(Dispatchers.IO) {+            runCatching {+                AlarmScheduler.scheduleSnooze(+                    ctx,+                    ClockRepository.get(ctx),+                    ringing,+                    ringing.snoozeMinutes,+                )+            }.onFailure {+                Log.error(TAG, "Alarm ${ringing.id}: could not schedule snooze", it)+            }+            withContext(Dispatchers.Main) { finish() }         }-        val pendingIntent = PendingIntent.getBroadcast(-            this,-            alarmId.toInt(),-            intent,-            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,-        )-        val alarmManager = getSystemService(AlarmManager::class.java)-        val info = AlarmManager.AlarmClockInfo(triggerMillis, pendingIntent)-        alarmManager.setAlarmClock(info, pendingIntent)-        finish()+    }++    private companion object {+        const val TAG = "AlarmActivity"     } }
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 68cffeed14..7a95ab05a7 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmReceiver.kt@@ -1,27 +1,33 @@ package com.vayunmathur.clock.platform-import android.content.ActivityNotFoundException import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent+import android.content.ActivityNotFoundException import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Build-import com.vayunmathur.library.log.Log import androidx.core.app.NotificationCompat+import com.vayunmathur.clock.R import com.vayunmathur.clock.data.ClockRepository+import com.vayunmathur.clock.service.AlarmSoundService+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.ui.RINGTONE_SILENT import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch-import com.vayunmathur.clock.service.AlarmSoundService-import com.vayunmathur.clock.R  class AlarmReceiver : BroadcastReceiver() {     override fun onReceive(context: Context, intent: Intent) {         createNotificationChannels(context)         val alarmId = intent.getLongExtra("ALARM_ID", -1L)-        Log.status(TAG, "Alarm $alarmId fired (snooze=${intent.getBooleanExtra("IS_SNOOZE", false)})")+        if (alarmId == -1L) {+            Log.error(TAG, "Alarm fired without an id; ignoring")+            return+        }+        val isSnooze = intent.getBooleanExtra(AlarmScheduler.EXTRA_IS_SNOOZE, false)+        Log.status(TAG, "Alarm $alarmId fired (snooze=$isSnooze)")          // 1. Create the Intent for your "Ringing" Activity         val ringIntent = Intent(context, AlarmActivity::class.java).apply {@@ -37,8 +43,12 @@ class AlarmReceiver : BroadcastReceiver() {             PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE         ) +        // Only one alarm can ring at a time: retire whatever the previous ring left+        // behind (stale notification, second service start) before posting our own.+        stopPreviousRing(context)+         postRingNotification(context, intent, alarmId, pendingIntent)-        rescheduleAlarm(context, alarmId)+        rescheduleAlarm(context, alarmId, isSnooze)         startSoundService(context, alarmId)         startRingActivity(context, alarmId, ringIntent)     }@@ -49,22 +59,24 @@ class AlarmReceiver : BroadcastReceiver() {         alarmId: Long,         pendingIntent: PendingIntent,     ) {-        // 3. Build the Notification. For most alarms this is what actually rings: FLAG_INSISTENT+        // 3. Build the Notification. For most alarms this is the backstop: FLAG_INSISTENT         // below repeats the ring channel's sound until something cancels it, so the alarm sounds         // even when AlarmSoundService never reaches startForeground.         //-        // Gradual-volume alarms opt out. The ring channel's sound is fixed and plays at full-        // volume, so they would blast, cut to silence and then fade in from zero - the opposite-        // of the setting. They ring only once the service starts, and give up the safety net.-        // Read from the intent, not the database: putting a read in front of the ring is the-        // latency this whole design exists to avoid.+        // Gradual-volume alarms normally opt out. The ring channel's sound is fixed and plays at+        // full volume, so they would blast, cut to silence and then fade in from zero - the+        // opposite of the setting. That trade is only worth it when the service is likely to+        // take over: when its start was denied (or the fire carries no ringtone), an insistent+        // notification is the only sound there will ever be, so ring anyway.         val gradual = intent.getIntExtra(AlarmScheduler.EXTRA_GRADUAL_SECONDS, 0) > 0+        val silent = intent.getStringExtra(AlarmScheduler.EXTRA_RINGTONE_URI) == RINGTONE_SILENT+        val canStartService = canStartForegroundService(context)         // The label rides in the broadcast (like gradual seconds) so the ring shows it         // without a database read on the latency-sensitive fire path.         val label = intent.getStringExtra(AlarmScheduler.EXTRA_LABEL).orEmpty()         val builder = NotificationCompat.Builder(             context,-            if (gradual) ALARM_CHANNEL_ID else ALARM_RING_CHANNEL_ID,+            if (gradual && canStartService && !silent) ALARM_CHANNEL_ID else ALARM_RING_CHANNEL_ID,         )             .setSmallIcon(R.drawable.baseline_access_alarm_24)             .setContentTitle(context.getString(R.string.label_alarm))@@ -80,50 +92,73 @@ class AlarmReceiver : BroadcastReceiver() {             // dismiss path is missed (process killed before the UI ever appeared, say).             .setTimeoutAfter(RING_TIMEOUT_MS) -        // Show the alarm's own label; omit the line entirely when it is empty.-        if (label.isNotBlank()) {+        // Without the full-screen permission the ringing screen can only appear if the+        // background activity start below happens to be allowed, which off-screen it is+        // not. Say so on the notification itself: a log line is invisible to the user+        // sleeping through the alarm they thought they set.+        if (!canUseFullScreenIntent(context)) {+            builder.setContentText(+                label.ifBlank { context.getString(R.string.alarm_missing_fullscreen_text) }+            )+        } else if (label.isNotBlank()) {+            // Show the alarm's own label; omit the line entirely when it is empty.             builder.setContentText(label)         } -        warnIfFullscreenDenied(context, alarmId)         val notificationManager =             context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager         notificationManager.notify(             ALARM_RING_NOTIFICATION_ID,             builder.build().apply {-                if (!gradual) flags = flags or Notification.FLAG_INSISTENT+                if (!gradual || !canStartService || silent) {+                    flags = flags or Notification.FLAG_INSISTENT+                }             },         )     } -    private fun warnIfFullscreenDenied(context: Context, alarmId: Long) {+    private fun stopPreviousRing(context: Context) {+        // The service owns the sound once it is up; a second fire while it is still+        // playing used to leave both alarms ringing on top of each other.+        context.stopService(Intent(context, AlarmSoundService::class.java))+        (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)+            .cancel(ALARM_RING_NOTIFICATION_ID)+    }++    private fun canUseFullScreenIntent(context: Context): Boolean {+        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.UPSIDE_DOWN_CAKE) return true         val notificationManager =             context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager-        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE &&-            !notificationManager.canUseFullScreenIntent()-        ) {-            // Without it the ringing screen can only appear if the background activity start-            // below happens to be allowed, which off-screen it is not.-            Log.status(-                TAG,-                "Alarm $alarmId: USE_FULL_SCREEN_INTENT not granted; ringing UI may not appear",-            )-        }+        return notificationManager.canUseFullScreenIntent()+    }++    private fun canStartForegroundService(context: Context): Boolean {+        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return true+        return (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)+            .areNotificationsEnabled()     }      // Broad catch is deliberate: onReceive must not throw, and Room plus the     // scheduler throw undocumented RuntimeExceptions (not just SQLiteException).     @Suppress("TooGenericExceptionCaught")-    private fun rescheduleAlarm(context: Context, alarmId: Long) {+    private fun rescheduleAlarm(context: Context, alarmId: Long, isSnooze: Boolean) {         val repository = ClockRepository.get(context)         val pendingResult = goAsync()         CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {             try {                 val alarm = repository.getAlarm(alarmId)-                if (alarm.days == 0) {-                    repository.upsertAlarm(alarm.copy(enabled = false))+                if (isSnooze) {+                    // The snooze that just fired is spent; the alarm's own schedule was+                    // never touched (it lives on its own request code), so just clear it.+                    if (alarm.snoozedUntil != null) {+                        repository.upsertAlarm(alarm.copy(snoozedUntil = null))+                    }                 } else {-                    AlarmScheduler.schedule(context, alarm)+                    if (alarm.days == 0) {+                        repository.upsertAlarm(alarm.copy(enabled = false))+                    } else {+                        AlarmScheduler.schedule(context, alarm)+                    }                 }             } catch (e: Exception) {                 Log.error(TAG, "Alarm $alarmId: could not reschedule", e)
clock/src/main/java/com/vayunmathur/clock/platform/AlarmScheduler.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmScheduler.kt b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmScheduler.ktindex 836fc31fa9..87a24a4221 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/AlarmScheduler.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/AlarmScheduler.kt@@ -4,6 +4,7 @@ import android.app.PendingIntent import android.content.Context import android.content.Intent import com.vayunmathur.clock.data.Alarm+import com.vayunmathur.clock.data.ClockRepository import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDateTime import kotlinx.datetime.TimeZone@@ -12,6 +13,8 @@ import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import kotlin.time.Clock import kotlin.time.Duration.Companion.days+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Instant  object AlarmScheduler {     /**@@ -21,6 +24,19 @@ object AlarmScheduler {      */     const val EXTRA_GRADUAL_SECONDS = "GRADUAL_SECONDS"     const val EXTRA_LABEL = "ALARM_LABEL"+    const val EXTRA_RINGTONE_URI = "RINGTONE_URI"+    const val EXTRA_VIBRATE = "VIBRATE"++    /**+     * Marks the intent as the fire of a previously persisted snooze (as opposed to the+     * alarm's regular schedule). [AlarmReceiver] clears the stored snooze when it sees+     * this, so a regular fire does not clear a pending snooze and a snooze fire does.+     */+    const val EXTRA_IS_SNOOZE = "IS_SNOOZE"++    /** Distinct request codes so a snooze never overwrites the alarm's own schedule. */+    internal const val REQUEST_RING = 0+    internal const val REQUEST_SNOOZE = 1      fun schedule(context: Context, alarm: Alarm) {         val alarmManager = context.getSystemService(AlarmManager::class.java)@@ -29,11 +45,13 @@ object AlarmScheduler {             putExtra("ALARM_ID", alarm.id)             putExtra(EXTRA_GRADUAL_SECONDS, alarm.gradualVolumeSeconds)             putExtra(EXTRA_LABEL, alarm.name)+            putExtra(EXTRA_RINGTONE_URI, alarm.ringtoneUri)+            putExtra(EXTRA_VIBRATE, alarm.vibrate)         }-        +         val pendingIntent = PendingIntent.getBroadcast(             context,-            alarm.id.hashCode(), // Unique ID per alarm+            ringRequestCode(alarm.id),             intent,             PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE         )@@ -50,14 +68,91 @@ object AlarmScheduler {      fun cancel(context: Context, alarm: Alarm) {         val alarmManager = context.getSystemService(AlarmManager::class.java)+        cancelRing(context, alarmManager, alarm.id)+        cancelSnooze(context, alarmManager, alarm.id)+    }++    /**+     * Arms the snoozed ring as its own AlarmManager entry, on a distinct request+     * code so it cannot clobber the alarm's recurring schedule, and persists it+     * so [BootReceiver] can re-arm it after a reboot.+     */+    suspend fun scheduleSnooze(+        context: Context,+        repository: ClockRepository,+        alarm: Alarm,+        snoozeMinutes: Int,+    ): Long {+        val alarmManager = context.getSystemService(AlarmManager::class.java)+        val triggerMillis = Clock.System.now().plus(+            snoozeMinutes.coerceAtLeast(1).minutes+        ).toEpochMilliseconds()+        val intent = Intent(context, AlarmReceiver::class.java).apply {+            putExtra("ALARM_ID", alarm.id)+            putExtra(EXTRA_IS_SNOOZE, true)+            // Snooze builds its own intent rather than going through schedule(), so it has+            // to carry these itself or the snoozed alarm would ring with the wrong settings.+            putExtra(EXTRA_GRADUAL_SECONDS, alarm.gradualVolumeSeconds)+            putExtra(EXTRA_LABEL, alarm.name)+            putExtra(EXTRA_RINGTONE_URI, alarm.ringtoneUri)+            putExtra(EXTRA_VIBRATE, alarm.vibrate)+        }+        val pendingIntent = PendingIntent.getBroadcast(+            context,+            snoozeRequestCode(alarm.id),+            intent,+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(triggerMillis, pendingIntent), pendingIntent)+        repository.upsertAlarm(+            alarm.copy(snoozedUntil = Instant.fromEpochMilliseconds(triggerMillis))+        )+        return triggerMillis+    }++    /** Drops the persisted snooze without touching the alarm's own schedule. */+    suspend fun clearSnooze(+        context: Context,+        repository: ClockRepository,+        alarm: Alarm,+    ) {+        val alarmManager = context.getSystemService(AlarmManager::class.java)+        cancelSnooze(context, alarmManager, alarm.id)+        if (alarm.snoozedUntil != null) {+            repository.upsertAlarm(alarm.copy(snoozedUntil = null))+        }+    }++    internal fun ringRequestCode(alarmId: Long): Int = alarmId.toInt() * 2 + REQUEST_RING++    internal fun snoozeRequestCode(alarmId: Long): Int = alarmId.toInt() * 2 + REQUEST_SNOOZE++    private fun cancelRing(context: Context, alarmManager: AlarmManager, alarmId: Long) {         val intent = Intent(context, AlarmReceiver::class.java)         val pendingIntent = PendingIntent.getBroadcast(             context,-            alarm.id.hashCode(),+            ringRequestCode(alarmId),             intent,             PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE         )-        pendingIntent?.let { alarmManager.cancel(it) }+        pendingIntent?.let {+            alarmManager.cancel(it)+            it.cancel()+        }+    }++    private fun cancelSnooze(context: Context, alarmManager: AlarmManager, alarmId: Long) {+        val intent = Intent(context, AlarmReceiver::class.java)+        val pendingIntent = PendingIntent.getBroadcast(+            context,+            snoozeRequestCode(alarmId),+            intent,+            PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE+        )+        pendingIntent?.let {+            alarmManager.cancel(it)+            it.cancel()+        }     }      fun calculateNextTriggerMillis(alarm: Alarm): Long {
clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt b/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.ktindex c230b80f1a..4dfb3dcfb5 100644--- a/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt+++ b/clock/src/main/java/com/vayunmathur/clock/platform/BootReceiver.kt@@ -3,12 +3,13 @@ package com.vayunmathur.clock.platform import android.content.BroadcastReceiver import android.content.Context import android.content.Intent-import com.vayunmathur.library.log.Log import com.vayunmathur.clock.data.ClockRepository+import com.vayunmathur.library.log.Log import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch+import kotlin.time.Clock  class BootReceiver : BroadcastReceiver() {     // Broad catch is deliberate: onReceive must not throw, and Room throws@@ -23,9 +24,38 @@ class BootReceiver : BroadcastReceiver() {                 val pendingResult = goAsync()                 CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {                     try {-                        val enabled = repository.getAllAlarms().filter { it.enabled }-                        enabled.forEach { AlarmScheduler.schedule(context, it) }-                        Log.status(TAG, "${intent.action}: rescheduled ${enabled.size} alarm(s)")+                        val alarms = repository.getAllAlarms()+                        var rings = 0+                        var snoozes = 0+                        val now = Clock.System.now()+                        alarms.filter { it.enabled }.forEach { alarm ->+                            AlarmScheduler.schedule(context, alarm)+                            rings+++                            // Snoozes live in AlarmManager, which does not survive a+                            // reboot; the trigger time is persisted on the alarm, so+                            // re-arm those still in the future. Spent ones just clear.+                            val snoozedUntil = alarm.snoozedUntil+                            if (snoozedUntil != null) {+                                if (snoozedUntil > now) {+                                    AlarmScheduler.scheduleSnooze(+                                        context,+                                        repository,+                                        alarm,+                                        // scheduleSnooze recomputes from now; pass the+                                        // remaining whole minutes, at least one.+                                        ((snoozedUntil - now).inWholeMinutes).toInt()+                                            .coerceAtLeast(1),+                                    )+                                    snoozes+++                                } else {+                                    repository.upsertAlarm(alarm.copy(snoozedUntil = null))+                                }+                            }+                        }+                        Log.status(+                            TAG,+                            "${intent.action}: rescheduled $rings alarm(s) and $snoozes snooze(s)",+                        )                     } catch (e: Exception) {                         // Not expected at either action: ClockRepository is built with                         // useDeviceProtectedStorage = true precisely so the alarm database is
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 7b27f55c1d..22cfbab2e8 100644--- a/clock/src/main/java/com/vayunmathur/clock/service/AlarmSoundService.kt+++ b/clock/src/main/java/com/vayunmathur/clock/service/AlarmSoundService.kt@@ -11,7 +11,6 @@ import android.net.Uri import android.os.VibrationEffect import android.os.Vibrator import android.os.VibratorManager-import com.vayunmathur.library.log.Log import androidx.core.app.NotificationCompat import androidx.core.net.toUri import com.vayunmathur.clock.R@@ -19,6 +18,7 @@ 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.log.Log import com.vayunmathur.library.ui.RINGTONE_SILENT import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers@@ -31,7 +31,7 @@ import kotlinx.coroutines.withContext class AlarmSoundService : Service() {     private var mediaPlayer: MediaPlayer? = null     private var vibrator: Vibrator? = null-    private var started = false+    private var ringingForAlarmId: Long = -1L      /** Whether the MediaPlayer is actually producing sound, so the ring notification is spare. */     @Volatile@@ -79,21 +79,21 @@ class AlarmSoundService : Service() {             return START_NOT_STICKY         } -        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_NOT_STICKY+        if (ringingForAlarmId != -1L && ringingForAlarmId != alarmId) {+            // A second alarm has fired while the first is still ringing. The receiver+            // already stopped this service before posting the new ring, but the stop+            // is asynchronous (onDestroy runs on the main thread) while this start+            // can land first; without the guard both alarms play on top of each other.+            // The old ring loses: the ringing activity only ever shows the latest.+            stopRingLocked()         }-        started = true+        ringingForAlarmId = alarmId+        sounding = false          scope.launch {-            val alarm = if (alarmId != -1L) {-                runCatching {-                    ClockRepository.get(applicationContext).getAlarm(alarmId)-                }.getOrNull()-            } else null+            val alarm = runCatching {+                ClockRepository.get(applicationContext).getAlarm(alarmId)+            }.getOrNull()              val ringtoneUri = alarm?.ringtoneUri             val vibrate = alarm?.vibrate ?: true@@ -119,9 +119,18 @@ class AlarmSoundService : Service() {             // 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) {+            //+            // A gradual alarm's notification was posted silent and only becomes spare once+            // the fade actually starts; cancelling it unconditionally would leave a slow+            // prepare() with no sound at all. The receiver made that notification+            // insistent when the service was unlikely to start, so only cancel there.+            if (sounding) {                 cancelRingNotification()-            } else {+                // The looping player is the ring now: bound it like the notification,+                // which times out after ten minutes. Otherwise a missed alarm plays+                // until the process dies or the battery does.+                scheduleAutoStop(alarmId, RING_TIMEOUT_MS)+            } else if (!silent) {                 Log.error(TAG, "Alarm $alarmId: no ringtone played; leaving the ring notification up")             }         }@@ -153,6 +162,18 @@ class AlarmSoundService : Service() {         getSystemService(NotificationManager::class.java).cancel(ALARM_RING_NOTIFICATION_ID)     } +    /** Stops the ring after [timeoutMs] if nobody dismissed it first. */+    private fun scheduleAutoStop(alarmId: Long, timeoutMs: Long) {+        scope.launch {+            delay(timeoutMs)+            // Still the same ring: a newer alarm re-arms its own deadline.+            if (ringingForAlarmId == alarmId) {+                Log.status(TAG, "Alarm $alarmId: ringing timed out; stopping")+                stopSelf()+            }+        }+    }+     private fun resolveRingtone(uriString: String?): Uri? = when (uriString) {         null -> RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)             ?: RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)@@ -205,8 +226,18 @@ class AlarmSoundService : Service() {         vibrator?.vibrate(VibrationEffect.createWaveform(pattern, 0))     } +    /** Synchronous stop of the current ring, for the overlapping-alarm handover. */+    private fun stopRingLocked() {+        runCatching { mediaPlayer?.stop() }+        releasePlayer()+        runCatching { vibrator?.cancel() }+        vibrator = null+        sounding = false+    }+     override fun onDestroy() {         destroyed = true+        ringingForAlarmId = -1L         scope.cancel()         // stop() throws IllegalStateException unless prepared/started; an unguarded call         // would skip the vibrator cancel and super.onDestroy() below, wedging vibration on.@@ -221,6 +252,12 @@ class AlarmSoundService : Service() {      companion object {         const val NOTIFICATION_ID = 1001++        /**+         * Matches the receiver's bound: the insistent notification gives up after+         * ten minutes, so the looping player must not outlive it.+         */+        const val RING_TIMEOUT_MS = 10 * 60 * 1000L         private const val TAG = "AlarmSoundService"     } }
clock/src/main/java/com/vayunmathur/clock/ui/AlarmPage.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/AlarmPage.kt b/clock/src/main/java/com/vayunmathur/clock/ui/AlarmPage.ktindex e12b63b60b..f7a2f800a8 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/AlarmPage.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/AlarmPage.kt@@ -37,7 +37,11 @@ fun AlarmPage(backStack: NavBackStack<Route>, clockViewModel: ClockViewModel) {         if (result.resultCode == android.app.Activity.RESULT_OK) {             val picked = ringtonePickerResult(result.data)             clockViewModel.alarms.value.firstOrNull { it.id == pickingAlarmId }?.let { target ->-                clockViewModel.upsert(target.copy(ringtoneUri = picked))+                // Same reschedule requirement as setGradualVolumeSeconds below:+                // the fire intent carries the ringtone URI.+                val updated = target.copy(ringtoneUri = picked)+                if (updated.enabled) alarmScheduler.schedule(context, updated)+                clockViewModel.upsert(updated)             }         }         pickingAlarmId = null@@ -46,16 +50,26 @@ fun AlarmPage(backStack: NavBackStack<Route>, clockViewModel: ClockViewModel) {     val actions = remember(clockViewModel, context) {         object : AlarmActions {             private fun save(alarm: Alarm) {-                if (alarm.enabled) alarmScheduler.schedule(context, alarm)-                clockViewModel.upsert(alarm)+                // Snooze state belongs to the old schedule: re-arming the alarm+                // (new time, new days) drops any pending snooze with it.+                val cleared = if (alarm.snoozedUntil != null) alarm.copy(snoozedUntil = null) else alarm+                if (cleared.enabled) alarmScheduler.schedule(context, cleared)+                clockViewModel.upsert(cleared)             } -            override fun setName(alarm: Alarm, name: String) = save(alarm.copy(name = name))+            override fun setName(alarm: Alarm, name: String) {+                // The fire intent carries the label; reschedule like any sound-affecting edit.+                save(alarm.copy(name = name))+            }             override fun setTime(alarm: Alarm, time: LocalTime) = save(alarm.copy(time = time))             override fun setDays(alarm: Alarm, days: Int) = save(alarm.copy(days = days))              override fun setEnabled(alarm: Alarm, enabled: Boolean) {-                val updated = alarm.copy(enabled = enabled)+                // Toggling off also drops a pending snooze: the user silenced the alarm.+                val updated = alarm.copy(+                    enabled = enabled,+                    snoozedUntil = if (enabled) alarm.snoozedUntil else null,+                )                 if (enabled) alarmScheduler.schedule(context, updated) else alarmScheduler.cancel(context, updated)                 clockViewModel.upsert(updated)             }@@ -77,7 +91,10 @@ fun AlarmPage(backStack: NavBackStack<Route>, clockViewModel: ClockViewModel) {             }              override fun setVibrate(alarm: Alarm, vibrate: Boolean) {-                clockViewModel.upsert(alarm.copy(vibrate = vibrate))+                // The fire intent carries vibrate/ringtone so the receiver can ring+                // without a database read; a plain upsert would leave the already-+                // scheduled intent (and the snooze path) holding the old values.+                save(alarm.copy(vibrate = vibrate))             }              override fun setSnoozeMinutes(alarm: Alarm, minutes: Int) {
clock/src/main/java/com/vayunmathur/clock/ui/components/AlarmRingingScreen.kt
diff --git a/clock/src/main/java/com/vayunmathur/clock/ui/components/AlarmRingingScreen.kt b/clock/src/main/java/com/vayunmathur/clock/ui/components/AlarmRingingScreen.ktindex 6c7c7b8dfd..875f715dc9 100644--- a/clock/src/main/java/com/vayunmathur/clock/ui/components/AlarmRingingScreen.kt+++ b/clock/src/main/java/com/vayunmathur/clock/ui/components/AlarmRingingScreen.kt@@ -35,7 +35,8 @@ fun AlarmRingingScreen(     alarmName: String,     snoozeMinutes: Int,     onDismiss: () -> Unit,-    onSnooze: () -> Unit+    onSnooze: () -> Unit,+    snoozeEnabled: Boolean = true, ) {     // RAW SCAFFOLD EXCEPTION: full-screen alarm-ringing takeover — no top bar, nav,     // actions or FAB, just centered content with SpaceBetween. None of the shared@@ -67,7 +68,7 @@ fun AlarmRingingScreen(                 ) {                     Text(text = stringResource(R.string.button_stop), style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.ExtraBold)                 }-                FilledTonalButton(onClick = onSnooze, modifier = Modifier.fillMaxWidth().height(64.dp), shape = MaterialTheme.shapes.extraLarge) {+                FilledTonalButton(onClick = onSnooze, enabled = snoozeEnabled, modifier = Modifier.fillMaxWidth().height(64.dp), shape = MaterialTheme.shapes.extraLarge) {                     IconPause(); Spacer(modifier = Modifier.width(8.dp)); Text(text = stringResource(R.string.button_snooze, snoozeMinutes), style = MaterialTheme.typography.titleMedium)                 }             }
clock/src/main/res/values/strings.xml
diff --git a/clock/src/main/res/values/strings.xml b/clock/src/main/res/values/strings.xmlindex 6c6db26e0b..da4d46162b 100644--- a/clock/src/main/res/values/strings.xml+++ b/clock/src/main/res/values/strings.xml@@ -21,6 +21,8 @@     <!-- AlarmReceiver / AlarmSoundService: notifications shown when alarm triggers -->     <!-- Foreground service notification title while alarm is ringing -->     <string name="alarm_ringing_notification_title">Alarm is Ringing</string>+    <!-- AlarmReceiver: fallback line when USE_FULL_SCREEN_INTENT is denied and only a heads-up shows -->+    <string name="alarm_missing_fullscreen_text">Tap to open \u2014 full-screen alarm permission is off</string>      <!-- Notification channels: visible in system notification settings -->     <!-- System channel name for ongoing timers countdown notification -->@@ -99,6 +101,10 @@     <string name="time_pm">PM</string>     <!-- MainActivity: permission onboarding button to grant notification permission -->     <string name="grant_notifications_permission">Grant Notifications Permission</string>+    <!-- MainActivity: persistent banner while the full-screen alarm permission is revoked (API 34+) -->+    <string name="alarm_fullscreen_revoked">Full-screen alarms are off \u2014 ringing alarms won\u2019t pop up over the lock screen</string>+    <!-- MainActivity: action that opens the full-screen-intent settings page -->+    <string name="action_open_settings">Open settings</string>      <!-- App widgets -->     <!-- Widget picker label for analog clock widget -->