Modern Apps git

← Modern-Apps.git

calendar: schedule exact-alarm notifications for event reminders (recurring and one-off)

Commit
656a9d6d8ee095c12ad5c6a3a82ddb9e47994588
Author
Vayun Mathur <[email protected]>
When
2026-08-09 16:01 UTC (3 months ago)
Parents
69156aa

Diff

calendar/src/main/AndroidManifest.xml
diff --git a/calendar/src/main/AndroidManifest.xml b/calendar/src/main/AndroidManifest.xmlindex 25b8944f24..921ee2295c 100644--- a/calendar/src/main/AndroidManifest.xml+++ b/calendar/src/main/AndroidManifest.xml@@ -3,6 +3,10 @@      <uses-permission android:name="android.permission.READ_CALENDAR" />     <uses-permission android:name="android.permission.WRITE_CALENDAR" />+    <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />+    <uses-permission android:name="android.permission.USE_EXACT_ALARM" />+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />      <permission         android:name="com.vayunmathur.calendar.permissions.ACCESS_CALENDAR"@@ -80,6 +84,25 @@                 android:name="android.appwidget.provider"                 android:resource="@xml/calendar_glance_widget_info" />         </receiver>++        <!-- Fires event-reminder notifications from AlarmManager exact alarms. -->+        <receiver+            android:name=".util.ReminderReceiver"+            android:enabled="true"+            android:exported="false" />+        <!-- Reschedules reminder alarms after reboot / app update. -->+        <receiver+            android:name=".util.BootReceiver"+            android:enabled="true"+            android:directBootAware="true"+            android:exported="true">+            <intent-filter>+                <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />+                <action android:name="android.intent.action.BOOT_COMPLETED" />+                <action android:name="android.intent.action.QUICKBOOT_POWERON" />+                <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />+            </intent-filter>+        </receiver>         <activity             android:name=".intents.GetIntent"             android:exported="true"
calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt b/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.ktindex e1d5b86128..f5298aed74 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt@@ -1,11 +1,14 @@ package com.vayunmathur.calendar  import android.Manifest+import android.app.AlarmManager import android.content.Intent import android.content.pm.PackageManager import android.net.Uri+import android.os.Build import android.os.Bundle import android.provider.CalendarContract+import android.provider.Settings import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.rememberLauncherForActivityResult@@ -53,6 +56,20 @@ class MainActivity : ComponentActivity() {         super.onCreate(savedInstanceState)         updateWidgetPreviews(CalendarGlanceWidgetReceiver::class)         enableEdgeToEdge()++        // Reminder notifications rely on exact alarms; route the user to the+        // system toggle if the app doesn't yet hold that special access.+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+            val alarmManager = getSystemService(AlarmManager::class.java)+            if (alarmManager != null && !alarmManager.canScheduleExactAlarms()) {+                runCatching {+                    startActivity(Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM).apply {+                        data = Uri.fromParts("package", packageName, null)+                    })+                }+            }+        }+         handleIntent(intent)         setContent {             val permissions = arrayOf(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR)@@ -70,6 +87,23 @@ class MainActivity : ComponentActivity() {                 } else {                     val viewModel: CalendarViewModel = viewModel() +                    // Reminder notifications need runtime notification permission on+                    // Android 13+. Requested here (not gated) so the calendar still+                    // works if the user declines.+                    val notificationPermissionLauncher = rememberLauncherForActivityResult(+                        ActivityResultContracts.RequestPermission()+                    ) {}+                    LaunchedEffect(Unit) {+                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&+                            ContextCompat.checkSelfPermission(+                                this@MainActivity,+                                Manifest.permission.POST_NOTIFICATIONS,+                            ) != PackageManager.PERMISSION_GRANTED+                        ) {+                            notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)+                        }+                    }+                     LaunchedEffect(intent) {                         if (intent?.action == Intent.ACTION_VIEW && intent.type == "time/epoch") {                             intent.data?.lastPathSegment?.toLongOrNull()?.let { timestamp ->
calendar/src/main/java/com/vayunmathur/calendar/util/BootReceiver.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/BootReceiver.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/BootReceiver.ktnew file mode 100644index 0000000000..8236d2fd18--- /dev/null+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/BootReceiver.kt@@ -0,0 +1,36 @@+package com.vayunmathur.calendar.util++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++/**+ * Reschedules all event-reminder alarms after a reboot or app update, since+ * AlarmManager alarms don't survive either. Mirrors the clock app's+ * [com.vayunmathur.clock.util.BootReceiver] plus findfamily's+ * package-replaced handling.+ */+class BootReceiver : BroadcastReceiver() {+    override fun onReceive(context: Context, intent: Intent) {+        when (intent.action) {+            Intent.ACTION_BOOT_COMPLETED,+            Intent.ACTION_LOCKED_BOOT_COMPLETED,+            Intent.ACTION_MY_PACKAGE_REPLACED,+            "android.intent.action.QUICKBOOT_POWERON" -> {+                val pendingResult = goAsync()+                CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {+                    try {+                        ReminderScheduler.reconcileAll(context)+                    } catch (_: Exception) {+                    } finally {+                        pendingResult.finish()+                    }+                }+            }+        }+    }+}
calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.ktindex 97958ff3fd..c7fb89646c 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/CalendarViewModel.kt@@ -300,6 +300,7 @@ class CalendarViewModel(application: Application) :                     if (reminders != null) writeReminders(eventId, reminders)                 }                 _events.value = Event.getAllEvents(app)+                ReminderScheduler.reconcileAll(app, _events.value)                 updateWidgets()             } catch (e: Exception) {                 Log.e("CalendarViewModel", "Error upserting event", e)
calendar/src/main/java/com/vayunmathur/calendar/util/ReminderReceiver.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderReceiver.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderReceiver.ktnew file mode 100644index 0000000000..1cbb039809--- /dev/null+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderReceiver.kt@@ -0,0 +1,80 @@+package com.vayunmathur.calendar.util++import android.app.NotificationManager+import android.app.PendingIntent+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.text.format.DateFormat+import androidx.core.app.NotificationCompat+import com.vayunmathur.calendar.MainActivity+import com.vayunmathur.calendar.R+import com.vayunmathur.library.util.ensureNotificationChannel+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import java.util.Date++/**+ * Fires when an event reminder alarm scheduled by [ReminderScheduler] goes off.+ * Posts a notification, then re-reconciles so the next occurrence of a+ * recurring event is scheduled (a no-op for one-off events).+ */+class ReminderReceiver : BroadcastReceiver() {+    override fun onReceive(context: Context, intent: Intent) {+        val eventId = intent.getLongExtra(ReminderScheduler.EXTRA_EVENT_ID, -1L)+        val title = intent.getStringExtra(ReminderScheduler.EXTRA_TITLE)+            ?.takeIf { it.isNotBlank() }+            ?: context.getString(R.string.reminder_notification_default_title)+        val instanceStart = intent.getLongExtra(ReminderScheduler.EXTRA_INSTANCE_START, 0L)++        context.ensureNotificationChannel(+            CHANNEL_ID,+            context.getString(R.string.reminder_channel_name),+            NotificationManager.IMPORTANCE_HIGH,+            context.getString(R.string.reminder_channel_description),+        )++        val openIntent = Intent(context, MainActivity::class.java).apply {+            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP+        }+        val contentIntent = PendingIntent.getActivity(+            context,+            eventId.toInt(),+            openIntent,+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )++        val timeString = DateFormat.getTimeFormat(context).format(Date(instanceStart))+        val notification = NotificationCompat.Builder(context, CHANNEL_ID)+            .setSmallIcon(R.drawable.ic_reminder_notification)+            .setContentTitle(title)+            .setContentText(context.getString(R.string.reminder_notification_text, timeString))+            .setPriority(NotificationCompat.PRIORITY_HIGH)+            .setCategory(NotificationCompat.CATEGORY_EVENT)+            .setContentIntent(contentIntent)+            .setAutoCancel(true)+            .build()++        val notificationId = 31 * eventId.hashCode() + instanceStart.hashCode()+        context.getSystemService(NotificationManager::class.java)+            .notify(notificationId, notification)++        // Reschedule the following occurrence for recurring events. Runs in the+        // background via goAsync() because it queries the calendar provider.+        val pendingResult = goAsync()+        CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {+            try {+                ReminderScheduler.reconcileAll(context)+            } catch (_: Exception) {+            } finally {+                pendingResult.finish()+            }+        }+    }++    companion object {+        const val CHANNEL_ID = "calendar_reminders"+    }+}
calendar/src/main/java/com/vayunmathur/calendar/util/ReminderScheduler.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderScheduler.kt b/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderScheduler.ktnew file mode 100644index 0000000000..8f3f11750e--- /dev/null+++ b/calendar/src/main/java/com/vayunmathur/calendar/util/ReminderScheduler.kt@@ -0,0 +1,165 @@+package com.vayunmathur.calendar.util++import android.app.AlarmManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import com.vayunmathur.calendar.data.Event+import com.vayunmathur.calendar.data.Instance+import kotlin.time.Clock+import kotlin.time.Duration.Companion.days++/**+ * Schedules exact alarms for calendar event reminders, mirroring the clock+ * app's [com.vayunmathur.clock.util.AlarmScheduler].+ *+ * Reminders live in `CalendarContract.Reminders` but the provider never fires+ * them itself, so we translate each reminder offset into an [AlarmManager]+ * exact alarm that broadcasts to [ReminderReceiver].+ *+ * Both one-off and recurring events are supported:+ *  - One-off events schedule every future reminder offset directly.+ *  - Recurring events schedule the next upcoming occurrence per reminder+ *    offset (expanded via [Instance.getInstances], which already honors+ *    EXDATE). When one fires, [ReminderReceiver] re-runs [reconcileAll] so the+ *    following occurrence gets scheduled. Boot does the same.+ *+ * [reconcileAll] is a cancel-all-then-reschedule-all pass, which keeps state+ * correct across insert / update / delete / exdate without per-mutation+ * bookkeeping. The set of currently-scheduled request codes is persisted so a+ * later reconcile can cancel alarms belonging to events that no longer exist.+ */+object ReminderScheduler {+    const val EXTRA_EVENT_ID = "event_id"+    const val EXTRA_MINUTES = "minutes"+    const val EXTRA_INSTANCE_START = "instance_start"+    const val EXTRA_INSTANCE_END = "instance_end"+    const val EXTRA_TITLE = "title"++    private const val PREFS = "calendar_reminders"+    private const val KEY_SCHEDULED = "scheduled_request_codes"++    // How far ahead to look for the next occurrence of a recurring event.+    private val RECURRENCE_WINDOW = 400.days++    /** Convenience for boot / package-replaced: reschedule from the provider. */+    fun reconcileAll(context: Context) =+        reconcileAll(context, Event.getAllEvents(context))++    fun reconcileAll(context: Context, events: List<Event>) {+        val alarmManager = context.getSystemService(AlarmManager::class.java) ?: return+        cancelAllTracked(context, alarmManager)++        val nowMillis = Clock.System.now().toEpochMilliseconds()+        val scheduled = mutableSetOf<Int>()++        for (event in events) {+            val eventId = event.id ?: continue+            val offsets = event.reminders.distinct()+            if (offsets.isEmpty()) continue++            if (event.rrule == null) {+                for (minutes in offsets) {+                    val triggerAt = event.start - minutes.toLong() * 60_000L+                    if (triggerAt <= nowMillis) continue+                    val code = requestCode(eventId, minutes, event.start)+                    scheduleExact(+                        context, alarmManager, code, triggerAt,+                        eventId, minutes, event.start, event.end, event.title,+                    )+                    scheduled += code+                }+            } else {+                val now = Clock.System.now()+                val instances = Instance.getInstances(context, now, now + RECURRENCE_WINDOW)+                    .filter { it.eventID == eventId }+                    .sortedBy { it.begin }+                for (minutes in offsets) {+                    val next = instances.firstOrNull {+                        it.begin - minutes.toLong() * 60_000L > nowMillis+                    } ?: continue+                    val triggerAt = next.begin - minutes.toLong() * 60_000L+                    val code = requestCode(eventId, minutes, next.begin)+                    scheduleExact(+                        context, alarmManager, code, triggerAt,+                        eventId, minutes, next.begin, next.end, event.title,+                    )+                    scheduled += code+                }+            }+        }+        saveTracked(context, scheduled)+    }++    private fun scheduleExact(+        context: Context,+        alarmManager: AlarmManager,+        requestCode: Int,+        triggerAtMillis: Long,+        eventId: Long,+        minutes: Int,+        instanceStart: Long,+        instanceEnd: Long,+        title: String,+    ) {+        val intent = Intent(context, ReminderReceiver::class.java).apply {+            putExtra(EXTRA_EVENT_ID, eventId)+            putExtra(EXTRA_MINUTES, minutes)+            putExtra(EXTRA_INSTANCE_START, instanceStart)+            putExtra(EXTRA_INSTANCE_END, instanceEnd)+            putExtra(EXTRA_TITLE, title)+        }+        val pendingIntent = PendingIntent.getBroadcast(+            context,+            requestCode,+            intent,+            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+        )+        // canScheduleExactAlarms() may be false if the user hasn't granted the+        // exact-alarm special access; fall back to an inexact alarm rather than+        // crashing on the SecurityException setExactAndAllowWhileIdle throws.+        try {+            alarmManager.setExactAndAllowWhileIdle(+                AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent,+            )+        } catch (_: SecurityException) {+            alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent)+        }+    }++    private fun cancelAllTracked(context: Context, alarmManager: AlarmManager) {+        val codes = loadTracked(context)+        for (code in codes) {+            val intent = Intent(context, ReminderReceiver::class.java)+            val pendingIntent = PendingIntent.getBroadcast(+                context,+                code,+                intent,+                PendingIntent.FLAG_NO_CREATE or PendingIntent.FLAG_IMMUTABLE,+            )+            pendingIntent?.let { alarmManager.cancel(it) }+        }+    }++    private fun requestCode(eventId: Long, minutes: Int, instanceStart: Long): Int {+        var result = eventId.hashCode()+        result = 31 * result + minutes+        result = 31 * result + instanceStart.hashCode()+        return result+    }++    private fun prefs(context: Context) =+        context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)++    private fun loadTracked(context: Context): Set<Int> =+        prefs(context).getStringSet(KEY_SCHEDULED, emptySet())+            ?.mapNotNull { it.toIntOrNull() }+            ?.toSet()+            ?: emptySet()++    private fun saveTracked(context: Context, codes: Set<Int>) {+        prefs(context).edit()+            .putStringSet(KEY_SCHEDULED, codes.map { it.toString() }.toSet())+            .apply()+    }+}
calendar/src/main/res/drawable/ic_reminder_notification.xml
diff --git a/calendar/src/main/res/drawable/ic_reminder_notification.xml b/calendar/src/main/res/drawable/ic_reminder_notification.xmlnew file mode 100644index 0000000000..d51a9710ad--- /dev/null+++ b/calendar/src/main/res/drawable/ic_reminder_notification.xml@@ -0,0 +1,9 @@+<vector xmlns:android="http://schemas.android.com/apk/res/android"+    android:width="24dp"+    android:height="24dp"+    android:viewportWidth="24"+    android:viewportHeight="24">+    <path+        android:fillColor="#FFFFFF"+        android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.89,2 2,2zM18,16v-5c0,-3.07 -1.64,-5.64 -4.5,-6.32L13.5,4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.63,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2z" />+</vector>
calendar/src/main/res/values/strings.xml
diff --git a/calendar/src/main/res/values/strings.xml b/calendar/src/main/res/values/strings.xmlindex f8c9f24fe2..746608aa57 100644--- a/calendar/src/main/res/values/strings.xml+++ b/calendar/src/main/res/values/strings.xml@@ -309,4 +309,13 @@     <string name="widget_preview_event_3_title">Design review</string>     <!-- Widget preview sample event 3: time range -->     <string name="widget_preview_event_3_time">3:00 – 4:00 PM</string>++    <!-- ReminderReceiver: Notification channel name for event reminders. Noun phrase -->+    <string name="reminder_channel_name">Event Reminders</string>+    <!-- ReminderReceiver: Notification channel description for event reminders. Sentence -->+    <string name="reminder_channel_description">Reminders for upcoming calendar events</string>+    <!-- ReminderReceiver: Fallback notification title when an event has no title. Noun phrase -->+    <string name="reminder_notification_default_title">Event reminder</string>+    <!-- ReminderReceiver: Notification body. %1$s = formatted event start time, e.g. 3:00 PM -->+    <string name="reminder_notification_text">Starts at <xliff:g id="start_time" example="3:00 PM">%1$s</xliff:g></string> </resources>