Modern Apps git

← Modern-Apps.git

maps: add Live Update notifications to maps, fooddelivery, updater

Commit
552785739cf3fa54699256357ae7e912b1ed2845
Author
vayun-mathur <[email protected]>
When
2026-10-22 16:50 UTC (1 month ago)
Parents
bcfbcfc

Diff

fooddelivery/src/main/AndroidManifest.xml
diff --git a/fooddelivery/src/main/AndroidManifest.xml b/fooddelivery/src/main/AndroidManifest.xmlindex f2015cbaa3..9dd14c0681 100644--- a/fooddelivery/src/main/AndroidManifest.xml+++ b/fooddelivery/src/main/AndroidManifest.xml@@ -3,6 +3,8 @@      <uses-permission android:name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <!-- Live Updates (API 36 ProgressStyle promoted ongoing): install-time, no runtime prompt. -->+    <uses-permission android:name="android.permission.POST_PROMOTED_NOTIFICATIONS" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" /> 
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderLiveUpdate.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderLiveUpdate.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderLiveUpdate.ktindex 0e154152d5..4628e1d08c 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderLiveUpdate.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderLiveUpdate.kt@@ -5,32 +5,32 @@ import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent-import android.os.Build import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import com.vayunmathur.fooddelivery.MainActivity import com.vayunmathur.fooddelivery.R import com.vayunmathur.fooddelivery.data.Order import com.vayunmathur.fooddelivery.data.OrderStage+import com.vayunmathur.library.util.LiveUpdateSupport import com.vayunmathur.library.util.ensureNotificationChannel  /**  * Builds the ongoing "Live Update" order-tracking notification.  *  * On Android 16+ (API 36) it uses [NotificationCompat.ProgressStyle] with segmented- * milestones and requests promotion to an ongoing Live Update. Below that it degrades to- * a plain ongoing notification with a determinate progress bar showing the same fraction.+ * milestones and a status chip, and requests promotion to a Live Update — but only+ * where the platform supports it (see [LiveUpdateSupport]: the style is 36.0, the+ * promotion request is 36.1). Below 36 it degrades to a plain ongoing notification+ * with a determinate progress bar showing the same fraction.  */ object OrderLiveUpdate {     const val CHANNEL_ID = "order_tracking"     const val NOTIFICATION_ID = 4711     const val EXTRA_TRACK_ORDER_ID = "com.vayunmathur.fooddelivery.EXTRA_TRACK_ORDER_ID" -    // Android 16 Live Updates arrived in API 36; below this we fall back to a plain bar.-    private const val LIVE_UPDATE_SDK = 36--    // Ordered milestones the tracker advances through. PREPARING_SOON collapses onto-    // PREPARING, and PICKED_UP maps onto DRIVING for delivery (it means "on the way").+    // Stage labels double as the Live Update status chip. PREPARING_SOON collapses+    // onto PREPARING, and PICKED_UP maps onto DRIVING for delivery (it means+    // "on the way").     private val DELIVERY_MILESTONES = listOf(         OrderStage.PREPARING,         OrderStage.READY,@@ -69,9 +69,11 @@ object OrderLiveUpdate {             .setOngoing(true)             .setOnlyAlertOnce(true)             .setCategory(NotificationCompat.CATEGORY_PROGRESS)+            // Promotion requires a colorized notification with a content title.+            .setColorized(true)             .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE) -        if (Build.VERSION.SDK_INT >= LIVE_UPDATE_SDK) {+        if (LiveUpdateSupport.isStyleSupported()) {             val progressStyle = NotificationCompat.ProgressStyle()                 .setProgressSegments(                     List(milestones.size - 1) { NotificationCompat.ProgressStyle.Segment(1) }@@ -82,7 +84,11 @@ object OrderLiveUpdate {                 .setProgress(index)             builder.setStyle(progressStyle)             builder.setShortCriticalText(order.stage.label)-            builder.setRequestPromotedOngoing(true)+            // 36.1+ only, and only when the system will actually promote —+            // without this guard the platform call crashes on base 36.0.+            if (LiveUpdateSupport.canPostPromoted(context)) {+                builder.setRequestPromotedOngoing(true)+            }         } else {             val max = (milestones.size - 1).coerceAtLeast(1)             builder.setProgress(max, index, false)
library/src/main/java/com/vayunmathur/library/util/LiveUpdateSupport.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/LiveUpdateSupport.kt b/library/src/main/java/com/vayunmathur/library/util/LiveUpdateSupport.ktnew file mode 100644index 0000000000..9d2c377d20--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/util/LiveUpdateSupport.kt@@ -0,0 +1,59 @@+package com.vayunmathur.library.util++import android.app.NotificationManager+import android.content.Context+import android.os.Build+import android.os.ext.SdkExtensions+import androidx.annotation.ChecksSdkIntAtLeast+import androidx.annotation.RequiresApi+import androidx.core.content.getSystemService++/**+ * Version + eligibility guards for Android Live Update (promoted ongoing)+ * notifications (API 36 `ProgressStyle` + status chip).+ *+ * Version trap this isolates: [android.app.Notification.ProgressStyle],+ * `setShortCriticalText` and `canPostPromotedNotifications` are API 36.0, but+ * `setRequestPromotedOngoing` only exists on API 36.1 (QPR1). Calling it on+ * base Android 16 (36.0) throws `NoSuchMethodError`, so the style gate+ * ([isStyleSupported]) and the promotion gate ([isPromotedOngoingSupported])+ * must stay separate — a single `SDK_INT >= 36` check is a crash on 36.0.+ *+ * All three Live Update call sites (maps / fooddelivery / updater) go through+ * `NotificationCompat` and only touch the 36.x APIs inside these gates, with+ * the legacy `setProgress()` bar as the `< 36` fallback.+ */+object LiveUpdateSupport {+    /** Android 16 Live Updates arrived in API 36. */+    const val LIVE_UPDATE_SDK = 36++    /** True on API 36+: `ProgressStyle` + `setShortCriticalText` are safe (via compat). */+    @ChecksSdkIntAtLeast(api = LIVE_UPDATE_SDK)+    fun isStyleSupported(): Boolean = Build.VERSION.SDK_INT >= LIVE_UPDATE_SDK++    /**+     * True only where the platform `setRequestPromotedOngoing` method exists:+     * API 36.1+. Checked via the BAKLAVA extension version so 36.0 devices get+     * the Live Update style without promotion instead of a crash.+     */+    @ChecksSdkIntAtLeast(api = LIVE_UPDATE_SDK)+    fun isPromotedOngoingSupported(): Boolean {+        if (Build.VERSION.SDK_INT < LIVE_UPDATE_SDK) return false+        return SdkExtensions.getExtensionVersion(Build.VERSION_CODES.BAKLAVA) >= 1+    }++    /**+     * Whether the system will actually promote an ongoing notification right+     * now: a 36.1+ platform, the app declared `POST_PROMOTED_NOTIFICATIONS`,+     * and the user has not turned promoted notifications off.+     */+    fun canPostPromoted(context: Context): Boolean {+        if (!isPromotedOngoingSupported()) return false+        val manager = context.getSystemService<NotificationManager>() ?: return false+        return canPostPromotedOn36(manager)+    }++    @RequiresApi(LIVE_UPDATE_SDK)+    private fun canPostPromotedOn36(manager: NotificationManager): Boolean =+        manager.canPostPromotedNotifications()+}
maps/src/main/AndroidManifest.xml
diff --git a/maps/src/main/AndroidManifest.xml b/maps/src/main/AndroidManifest.xmlindex 4adb66fd92..222233ae1e 100644--- a/maps/src/main/AndroidManifest.xml+++ b/maps/src/main/AndroidManifest.xml@@ -8,6 +8,8 @@     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />     <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <!-- Live Updates (API 36 ProgressStyle promoted ongoing): install-time, no runtime prompt. -->+    <uses-permission android:name="android.permission.POST_PROMOTED_NOTIFICATIONS" />      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt b/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.ktindex 1d70d3925b..3ea8d481fa 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/NavigationService.kt@@ -10,6 +10,7 @@ import android.content.pm.ServiceInfo import android.os.IBinder import com.vayunmathur.library.log.Log import androidx.core.app.NotificationCompat+import com.vayunmathur.library.util.LiveUpdateSupport import com.vayunmathur.maps.MainActivity import com.vayunmathur.maps.R import com.vayunmathur.maps.util.RouteService.TravelMode@@ -205,23 +206,56 @@ class NavigationService : Service() {         val destLabel = NavigationSessionManager.session.value.destinationName             ?: getString(R.string.nav_default_destination) -        val (title, content, progressPercent, smallIcon) = describe(state, mode, destLabel)+        val (title, content, progressPercent, chipText, smallIcon) = describe(state, mode, destLabel)+        val isOngoing = state !is NavigationSessionManager.NavState.Arrived &&+            state !is NavigationSessionManager.NavState.Failed          val builder = NotificationCompat.Builder(this, CHANNEL_ID)             .setContentTitle(title)             .setContentText(content)             .setSmallIcon(smallIcon)-            .setOngoing(state !is NavigationSessionManager.NavState.Arrived &&-                        state !is NavigationSessionManager.NavState.Failed)+            .setOngoing(isOngoing)             .setSilent(true)             .setOnlyAlertOnce(true)             .setContentIntent(tapIntent)             .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)+            // Promotion requires a colorized notification with a content title.+            .setColorized(true)+            .setCategory(NotificationCompat.CATEGORY_NAVIGATION)             .addAction(NO_ICON, getString(R.string.nav_action_end), stopIntent)          builder.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) -        progressPercent?.let { p -> builder.setProgress(FULL_PROGRESS_PERCENT, p, false) }+        if (LiveUpdateSupport.isStyleSupported()) {+            // Live Update (API 36): determinate ProgressStyle with the route+            // fraction and a status chip showing the next-maneuver distance.+            // Compat progress is in whole-percentage units (one segment of 100).+            // Terminal states use a plain style with no tracker; Failed is+            // never promoted.+            val navigating = state as? NavigationSessionManager.NavState.Navigating+            val percent = navigating?.progress?.let {+                (it.fractionComplete * PERCENT_SCALE).roundToInt()+                    .coerceIn(0, FULL_PROGRESS_PERCENT)+            } ?: if (state is NavigationSessionManager.NavState.Arrived) {+                FULL_PROGRESS_PERCENT+            } else {+                0+            }+            builder.setStyle(+                NotificationCompat.ProgressStyle()+                    .setProgressSegments(listOf(NotificationCompat.ProgressStyle.Segment(100)))+                    .setProgress(percent),+            )+            if (chipText != null) builder.setShortCriticalText(chipText)+            if (isOngoing && state !is NavigationSessionManager.NavState.Failed &&+                LiveUpdateSupport.canPostPromoted(this)+            ) {+                // 36.1+ only behind canPostPromoted — unguarded this crashes on 36.0.+                builder.setRequestPromotedOngoing(true)+            }+        } else {+            progressPercent?.let { p -> builder.setProgress(FULL_PROGRESS_PERCENT, p, false) }+        }         return builder.build()     } @@ -229,6 +263,8 @@ class NavigationService : Service() {         val title: String,         val content: String,         val progressPercent: Int?,+        /** Live Update status chip (API 36): next-maneuver distance, or null for no chip. */+        val chipText: String?,         val smallIcon: Int,     ) @@ -266,7 +302,7 @@ class NavigationService : Service() {     }      private fun idleInfo(defaultIcon: Int) = NotificationInfo(-        getString(R.string.nav_status_idle), "", null, defaultIcon,+        getString(R.string.nav_status_idle), "", null, null, defaultIcon,     )      private fun statusInfo(@@ -274,7 +310,8 @@ class NavigationService : Service() {         content: String,         progressPercent: Int?,         smallIcon: Int,-    ) = NotificationInfo(title, content, progressPercent, smallIcon)+        chipText: String? = null,+    ) = NotificationInfo(title, content, progressPercent, chipText, smallIcon)      private fun navigatingInfo(         state: NavigationSessionManager.NavState.Navigating,@@ -284,26 +321,28 @@ class NavigationService : Service() {     ): NotificationInfo {         val p = state.progress         val percent = (p.fractionComplete * PERCENT_SCALE).roundToInt().coerceIn(0, FULL_PROGRESS_PERCENT)+        // Status chip: the glanceable next-maneuver distance (e.g. "2 km").+        val chip = formatDistance(p.distanceToNextManeuver)         val distRemaining = formatDistance(p.distanceRemaining)         val etaText = formatEta(p.etaEpochMs)         val route = NavigationSessionManager.session.value.route         val currentStep = route?.step?.getOrNull(p.currentStepIndex)         return when (mode) {-            TravelMode.DRIVE -> driveInfo(currentStep, destLabel, p, etaText, percent, defaultIcon)+            TravelMode.DRIVE -> driveInfo(currentStep, destLabel, p, etaText, percent, chip, defaultIcon)             TravelMode.WALK -> progressInfo(                 getString(R.string.nav_walk_title_format, destLabel),-                percent, distRemaining, etaText, defaultIcon,+                percent, distRemaining, etaText, chip, defaultIcon,             )             TravelMode.BICYCLE -> progressInfo(                 getString(R.string.nav_bike_title_format, destLabel),-                percent, distRemaining, etaText, defaultIcon,+                percent, distRemaining, etaText, chip, defaultIcon,             )             TravelMode.TRANSIT -> transitInfo(-                currentStep, destLabel, percent, distRemaining, etaText, defaultIcon,+                currentStep, destLabel, percent, distRemaining, etaText, chip, defaultIcon,             )             null -> progressInfo(                 getString(R.string.nav_destination_format, destLabel),-                percent, distRemaining, etaText, defaultIcon,+                percent, distRemaining, etaText, chip, defaultIcon,             )         }     }@@ -314,6 +353,7 @@ class NavigationService : Service() {         p: NavigationProgress,         etaText: String,         percent: Int,+        chipText: String?,         defaultIcon: Int,     ): NotificationInfo {         val title = currentStep?.navInstruction?.instructions?.takeIf { it.isNotBlank() }@@ -323,7 +363,7 @@ class NavigationService : Service() {             formatDistance(p.distanceToNextManeuver),             etaText,         )-        return NotificationInfo(title, content, percent, defaultIcon)+        return NotificationInfo(title, content, percent, chipText, defaultIcon)     }      private fun progressInfo(@@ -331,11 +371,12 @@ class NavigationService : Service() {         percent: Int,         distRemaining: String,         etaText: String,+        chipText: String?,         defaultIcon: Int,     ): NotificationInfo = NotificationInfo(         title,         getString(R.string.nav_progress_content_format, percent, distRemaining, etaText),-        percent, defaultIcon,+        percent, chipText, defaultIcon,     )      private fun transitInfo(@@ -344,6 +385,7 @@ class NavigationService : Service() {         percent: Int,         distRemaining: String,         etaText: String,+        chipText: String?,         defaultIcon: Int,     ): NotificationInfo {         val transitTitle = currentStep?.transitDetails?.transitLine?.name@@ -353,7 +395,7 @@ class NavigationService : Service() {         return NotificationInfo(             transitTitle,             getString(R.string.nav_progress_content_format, percent, distRemaining, etaText),-            percent, defaultIcon,+            percent, chipText, defaultIcon,         )     } 
updater/src/main/AndroidManifest.xml
diff --git a/updater/src/main/AndroidManifest.xml b/updater/src/main/AndroidManifest.xmlindex 409ecec25e..56b995ba2b 100644--- a/updater/src/main/AndroidManifest.xml+++ b/updater/src/main/AndroidManifest.xml@@ -4,6 +4,8 @@     <uses-permission android:name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />     <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <!-- Live Updates (API 36 ProgressStyle promoted ongoing): install-time, no runtime prompt. -->+    <uses-permission android:name="android.permission.POST_PROMOTED_NOTIFICATIONS" />     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
updater/src/main/java/com/vayunmathur/updater/notifications/UpdateNotifications.kt
diff --git a/updater/src/main/java/com/vayunmathur/updater/notifications/UpdateNotifications.kt b/updater/src/main/java/com/vayunmathur/updater/notifications/UpdateNotifications.ktindex d8ba9020b4..d5fed0849a 100644--- a/updater/src/main/java/com/vayunmathur/updater/notifications/UpdateNotifications.kt+++ b/updater/src/main/java/com/vayunmathur/updater/notifications/UpdateNotifications.kt@@ -8,6 +8,7 @@ import android.content.Intent import com.vayunmathur.library.log.Log import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat+import com.vayunmathur.library.util.LiveUpdateSupport import com.vayunmathur.library.util.ensureNotificationChannel import com.vayunmathur.updater.MainActivity import com.vayunmathur.updater.R@@ -54,19 +55,52 @@ object UpdateNotifications {      *      * [percent] below zero renders as indeterminate, which is what a stage with no measurable      * length should look like rather than a bar frozen at zero.+     *+     * On Android 16+ (API 36) it uses [NotificationCompat.ProgressStyle] with a status+     * chip showing the percent, and requests promotion to a Live Update where the+     * platform supports it (see [LiveUpdateSupport]: style is 36.0, the promotion+     * request is 36.1). Below 36 it is the same determinate bar as before.      */-    fun progress(context: Context, title: String, percent: Int): Notification =-        NotificationCompat.Builder(context, CHANNEL_PROGRESS)+    fun progress(context: Context, title: String, percent: Int): Notification {+        val indeterminate = percent < 0+        val builder = NotificationCompat.Builder(context, CHANNEL_PROGRESS)             .setContentTitle(title)             .setSmallIcon(android.R.drawable.stat_sys_download)             .setCategory(NotificationCompat.CATEGORY_PROGRESS)-            .setProgress(MAX_PROGRESS, percent.coerceIn(0, MAX_PROGRESS), percent < 0)+            // Promotion requires a colorized notification with a content title.+            .setColorized(true)             .setOngoing(true)             // Without this every progress edit re-alerts, several times a second.             .setOnlyAlertOnce(true)             .setContentIntent(openApp(context))             .setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE)-            .build()++        if (LiveUpdateSupport.isStyleSupported()) {+            // Compat progress is in whole-percentage units (one segment of 100).+            if (indeterminate) {+                builder.setStyle(+                    NotificationCompat.ProgressStyle().setProgressIndeterminate(true),+                )+            } else {+                val clamped = percent.coerceIn(0, MAX_PROGRESS)+                builder.setStyle(+                    NotificationCompat.ProgressStyle()+                        .setProgressSegments(+                            listOf(NotificationCompat.ProgressStyle.Segment(MAX_PROGRESS)),+                        )+                        .setProgress(clamped),+                )+                builder.setShortCriticalText("$clamped%")+            }+            // 36.1+ only behind canPostPromoted — unguarded this crashes on 36.0.+            if (LiveUpdateSupport.canPostPromoted(context)) {+                builder.setRequestPromotedOngoing(true)+            }+        } else {+            builder.setProgress(MAX_PROGRESS, percent.coerceIn(0, MAX_PROGRESS), indeterminate)+        }+        return builder.build()+    }      fun updateProgress(context: Context, title: String, percent: Int) {         post(context, ID_PROGRESS, progress(context, title, percent))