Modern Apps git

← Modern-Apps.git

fooddelivery: add live order tracker notification (Android 16 Live Update)

Commit
d4a328d44526705ef4d459e26f7d8a003886e524
Author
Vayun Mathur <[email protected]>
When
2026-08-13 02:41 UTC (3 months ago)
Parents
1788ee3

Diff

fooddelivery/src/main/AndroidManifest.xml
diff --git a/fooddelivery/src/main/AndroidManifest.xml b/fooddelivery/src/main/AndroidManifest.xmlindex 2fde229b59..77d7dc5b36 100644--- a/fooddelivery/src/main/AndroidManifest.xml+++ b/fooddelivery/src/main/AndroidManifest.xml@@ -2,6 +2,9 @@ <manifest xmlns:android="http://schemas.android.com/apk/res/android">      <uses-permission android:name="android.permission.INTERNET" />+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />      <application         android:allowBackup="false"@@ -21,6 +24,15 @@                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>++        <service+            android:name=".notifications.OrderTrackingService"+            android:exported="false"+            android:foregroundServiceType="specialUse">+            <property+                android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"+                android:value="order_tracking" />+        </service>     </application>  </manifest>
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.ktindex 56dd9d9fb8..95af4dcba3 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/MainActivity.kt@@ -1,14 +1,23 @@ package com.vayunmathur.fooddelivery +import android.Manifest import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.os.Build import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge+import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalContext+import androidx.core.content.ContextCompat import com.stripe.android.PaymentConfiguration import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.IconHome@@ -24,6 +33,7 @@ import com.vayunmathur.library.util.rememberNavBackStack import com.vayunmathur.fooddelivery.api.BitesApi import com.vayunmathur.fooddelivery.data.CartItem import com.vayunmathur.fooddelivery.data.CartStore+import com.vayunmathur.fooddelivery.notifications.OrderLiveUpdate import com.vayunmathur.fooddelivery.ui.AccountScreen import com.vayunmathur.fooddelivery.ui.CartScreen import com.vayunmathur.fooddelivery.ui.CheckoutScreen@@ -48,8 +58,18 @@ sealed interface Route : NavKey { }  class MainActivity : ComponentActivity() {+    // The order to open on the tracking screen, set from a notification tap. Held as+    // Compose state so onNewIntent can push a new deep link into the running UI.+    private val trackOrderId = mutableStateOf<Int?>(null)++    private val requestNotificationPermission =+        registerForActivityResult(ActivityResultContracts.RequestPermission()) { }+     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)++        trackOrderId.value = intent.trackOrderIdOrNull()+        requestNotificationPermissionIfNeeded()         // api.deliverycollective.com is on AWS Elastic Beanstalk and serves an ACM cert         // chaining to Amazon Root CA 1, which FIRST_PARTY (ISRG + GTS only) doesn't carry —         // pinning to it fails the handshake before any request goes out. STANDARD adds the@@ -70,16 +90,39 @@ class MainActivity : ComponentActivity() {          setContent {             DynamicTheme {-                FoodDeliveryApp()+                FoodDeliveryApp(trackOrderId)             }         }     }++    override fun onNewIntent(intent: Intent) {+        super.onNewIntent(intent)+        setIntent(intent)+        intent.trackOrderIdOrNull()?.let { trackOrderId.value = it }+    }++    private fun requestNotificationPermissionIfNeeded() {+        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return+        val granted = ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) ==+            PackageManager.PERMISSION_GRANTED+        if (!granted) requestNotificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)+    } } +private fun Intent.trackOrderIdOrNull(): Int? =+    getIntExtra(OrderLiveUpdate.EXTRA_TRACK_ORDER_ID, -1).takeIf { it > 0 }+ @Composable-private fun FoodDeliveryApp() {+private fun FoodDeliveryApp(trackOrderId: MutableState<Int?>) {     val context = LocalContext.current     val backStack = rememberNavBackStack<Route>(Route.Home)++    // A notification tap deep-links to that order's tracking screen.+    LaunchedEffect(trackOrderId.value) {+        val id = trackOrderId.value ?: return@LaunchedEffect+        backStack.add(Route.OrderTracking(id))+        trackOrderId.value = null+    }     val currentPage = backStack.backStack.last()     val cart = remember { mutableStateListOf<CartItem>().also { it.addAll(CartStore.getAll(context)) } } 
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.ktnew file mode 100644index 0000000000..0e154152d5--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderLiveUpdate.kt@@ -0,0 +1,129 @@+package com.vayunmathur.fooddelivery.notifications++import android.app.Notification+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.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.+ */+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").+    private val DELIVERY_MILESTONES = listOf(+        OrderStage.PREPARING,+        OrderStage.READY,+        OrderStage.DRIVING,+        OrderStage.ARRIVING,+        OrderStage.DELIVERED,+    )+    private val PICKUP_MILESTONES = listOf(+        OrderStage.PREPARING,+        OrderStage.READY,+        OrderStage.PICKED_UP,+    )++    fun ensureChannel(context: Context) {+        context.ensureNotificationChannel(+            id = CHANNEL_ID,+            name = context.getString(R.string.order_tracking_channel),+            importance = NotificationManager.IMPORTANCE_LOW,+            description = context.getString(R.string.order_tracking_channel_desc),+        )+    }++    fun build(context: Context, order: Order): Notification {+        ensureChannel(context)++        val milestones = if (order.isDelivery) DELIVERY_MILESTONES else PICKUP_MILESTONES+        val index = milestoneIndex(order, milestones)+        val title = order.merchant?.name?.takeIf { it.isNotBlank() }+            ?: context.getString(R.string.tracking)++        val builder = NotificationCompat.Builder(context, CHANNEL_ID)+            .setSmallIcon(R.drawable.ic_launcher_foreground)+            .setContentTitle(title)+            .setContentText(statusText(context, order))+            .setContentIntent(contentIntent(context, order.id))+            .setOngoing(true)+            .setOnlyAlertOnce(true)+            .setCategory(NotificationCompat.CATEGORY_PROGRESS)+            .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)++        if (Build.VERSION.SDK_INT >= LIVE_UPDATE_SDK) {+            val progressStyle = NotificationCompat.ProgressStyle()+                .setProgressSegments(+                    List(milestones.size - 1) { NotificationCompat.ProgressStyle.Segment(1) }+                )+                .setProgressPoints(+                    milestones.indices.map { NotificationCompat.ProgressStyle.Point(it) }+                )+                .setProgress(index)+            builder.setStyle(progressStyle)+            builder.setShortCriticalText(order.stage.label)+            builder.setRequestPromotedOngoing(true)+        } else {+            val max = (milestones.size - 1).coerceAtLeast(1)+            builder.setProgress(max, index, false)+        }++        return builder.build()+    }++    fun cancel(context: Context) {+        NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)+    }++    private fun contentIntent(context: Context, orderId: Int): PendingIntent {+        val intent = Intent(context, MainActivity::class.java).apply {+            flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP+            putExtra(EXTRA_TRACK_ORDER_ID, orderId)+        }+        return PendingIntent.getActivity(+            context,+            orderId,+            intent,+            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+        )+    }++    private fun statusText(context: Context, order: Order): String {+        val status = order.displayStatus+        val eta = order.etaMillis+        if (order.stage != OrderStage.DELIVERED && eta != null) {+            val minutes = ((eta - System.currentTimeMillis()) / 60_000L).toInt()+            if (minutes > 0) return context.getString(R.string.notif_status_eta, status, minutes)+        }+        return status+    }++    private fun milestoneIndex(order: Order, milestones: List<OrderStage>): Int {+        val mapped = when (order.stage) {+            OrderStage.PREPARING_SOON -> OrderStage.PREPARING+            OrderStage.PICKED_UP -> if (order.isDelivery) OrderStage.DRIVING else OrderStage.PICKED_UP+            else -> order.stage+        }+        return milestones.indexOf(mapped).coerceAtLeast(0)+    }+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderTrackingService.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderTrackingService.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderTrackingService.ktnew file mode 100644index 0000000000..682fd576dc--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/notifications/OrderTrackingService.kt@@ -0,0 +1,144 @@+package com.vayunmathur.fooddelivery.notifications++import android.app.Notification+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.Build+import android.os.IBinder+import android.util.Log+import androidx.core.app.NotificationManagerCompat+import com.vayunmathur.fooddelivery.api.BitesApi+import com.vayunmathur.fooddelivery.data.Order+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++/**+ * Foreground service that keeps the [OrderLiveUpdate] notification current while an order+ * is in flight, even with the app backgrounded. It re-reads the same `/orders/past/all`+ * list the tracking screen polls and re-finds the order, updating every [POLL_MS] until+ * the order is done or gone, then stops itself.+ *+ * Foreground type is `specialUse`: we poll an API on a delivery-length timescale, so+ * neither `location` (we read no device location) nor the time-limited `shortService` /+ * `dataSync` types fit.+ */+class OrderTrackingService : Service() {+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+    private var pollJob: Job? = null+    private var trackedOrderId: Int = -1++    override fun onBind(intent: Intent?): IBinder? = null++    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+        val orderId = intent?.getIntExtra(EXTRA_ORDER_ID, -1) ?: -1+        if (orderId <= 0) {+            stopSelf()+            return START_NOT_STICKY+        }++        // Satisfy the startForeground deadline immediately with a placeholder; the first+        // poll replaces it with real data a moment later.+        try {+            startForegroundCompat(OrderLiveUpdate.build(this, Order(id = orderId)))+        } catch (e: Exception) {+            Log.e(TAG, "startForeground failed", e)+            stopSelf()+            return START_NOT_STICKY+        }++        // Idempotent: a repeat start for the same order just refreshes, no new loop.+        if (orderId == trackedOrderId && pollJob?.isActive == true) {+            return START_REDELIVER_INTENT+        }+        trackedOrderId = orderId+        pollJob?.cancel()+        pollJob = scope.launch { pollLoop(orderId) }+        return START_REDELIVER_INTENT+    }++    private suspend fun pollLoop(orderId: Int) {+        while (true) {+            val order = runCatching {+                BitesApi.getOrders().firstOrNull { it.id == orderId }+            }.getOrNull()++            if (order == null) {+                Log.d(TAG, "order $orderId not found; stopping")+                finish()+                return+            }++            Log.d(TAG, "order $orderId stage=${order.stage} eta=${order.etaMillis}")+            notify(OrderLiveUpdate.build(this, order))++            if (order.isDone) {+                Log.d(TAG, "order $orderId done; stopping")+                // Leave the terminal update visible briefly, then clear it.+                delay(TERMINAL_LINGER_MS)+                finish()+                return+            }+            delay(POLL_MS)+        }+    }++    private fun notify(notification: Notification) {+        // notify() needs POST_NOTIFICATIONS on API 33+; without it the foreground+        // placeholder simply stays put rather than crashing.+        try {+            NotificationManagerCompat.from(this).notify(OrderLiveUpdate.NOTIFICATION_ID, notification)+        } catch (e: SecurityException) {+            Log.w(TAG, "notify skipped (no permission)", e)+        }+    }++    private fun finish() {+        OrderLiveUpdate.cancel(this)+        stopForeground(STOP_FOREGROUND_REMOVE)+        stopSelf()+    }++    private fun startForegroundCompat(notification: Notification) {+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+            startForeground(+                OrderLiveUpdate.NOTIFICATION_ID,+                notification,+                ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE,+            )+        } else {+            startForeground(OrderLiveUpdate.NOTIFICATION_ID, notification)+        }+    }++    override fun onDestroy() {+        scope.cancel()+        super.onDestroy()+    }++    companion object {+        private const val TAG = "OrderTrackingService"++        /** Mirrors OrderTrackingScreen.POLL_MS. */+        private const val POLL_MS = 15_000L+        private const val TERMINAL_LINGER_MS = 5_000L+        private const val EXTRA_ORDER_ID = "order_id"++        fun start(context: Context, orderId: Int?) {+            if (orderId == null || orderId <= 0) return+            val intent = Intent(context, OrderTrackingService::class.java)+                .putExtra(EXTRA_ORDER_ID, orderId)+            context.startForegroundService(intent)+        }++        fun stop(context: Context) {+            context.stopService(Intent(context, OrderTrackingService::class.java))+        }+    }+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.ktindex 0386d0a39b..d712fe1cb8 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/CheckoutScreen.kt@@ -59,6 +59,7 @@ import com.vayunmathur.fooddelivery.data.Customer import com.vayunmathur.fooddelivery.data.Deal import com.vayunmathur.fooddelivery.data.OrderRewards import com.vayunmathur.fooddelivery.data.CheckoutResponse+import com.vayunmathur.fooddelivery.notifications.OrderTrackingService import android.util.Log import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay@@ -210,6 +211,7 @@ fun CheckoutScreen(         when (result) {             is PaymentSheetResult.Completed -> {                 orderSuccess = true+                OrderTrackingService.start(context, checkoutResponse?.order?.id)                 onOrderPlaced()             }             is PaymentSheetResult.Canceled -> {
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.ktindex 6324053521..0d6f6196a6 100644--- a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/ui/OrderTrackingScreen.kt@@ -62,6 +62,7 @@ import com.vayunmathur.fooddelivery.R import com.vayunmathur.fooddelivery.api.BitesApi import com.vayunmathur.fooddelivery.data.Order import com.vayunmathur.fooddelivery.data.OrderStage+import com.vayunmathur.fooddelivery.notifications.OrderTrackingService import kotlinx.coroutines.delay import kotlin.time.Instant import com.vayunmathur.library.ui.DateString@@ -86,6 +87,9 @@ fun OrderTrackingScreen(orderId: Int, onBack: () -> Unit) {     var loading by remember { mutableStateOf(true) }      LaunchedEffect(orderId) {+        // Keep the background Live Update tracker running for this order too, so tracking+        // opened from the Orders tab (or a re-opened app) is covered. Idempotent.+        OrderTrackingService.start(context, orderId)         while (true) {             val found = BitesApi.getOrders().firstOrNull { it.id == orderId }             order = found
fooddelivery/src/main/res/values/strings.xml
diff --git a/fooddelivery/src/main/res/values/strings.xml b/fooddelivery/src/main/res/values/strings.xmlindex 1a5096518c..cae873e1cd 100644--- a/fooddelivery/src/main/res/values/strings.xml+++ b/fooddelivery/src/main/res/values/strings.xml@@ -104,4 +104,8 @@     <string name="gate">Gate: %1$s</string>     <string name="back">%1$s%% back</string>     <string name="select_up_to">Select up to %1$s</string>+    <string name="order_tracking_channel">Order tracking</string>+    <string name="order_tracking_channel_desc">Ongoing updates while your order is on the way</string>+    <!-- %1$s = status label e.g. Driving to you, %2$d = minutes remaining -->+    <string name="notif_status_eta">%1$s · %2$d min</string> </resources>