Modern Apps git

← Modern-Apps.git

taxi: add live ride tracker notification (Android 16 Live Update)

Commit
6cff646f69e28f1f16038e0c75a4d43e1bd77e2c
Author
Vayun Mathur <[email protected]>
When
2026-08-13 02:46 UTC (3 months ago)
Parents
d4a328d

Diff

taxi/src/main/AndroidManifest.xml
diff --git a/taxi/src/main/AndroidManifest.xml b/taxi/src/main/AndroidManifest.xmlindex 8b60c37ba9..ab7de6b5f0 100644--- a/taxi/src/main/AndroidManifest.xml+++ b/taxi/src/main/AndroidManifest.xml@@ -4,6 +4,9 @@     <uses-permission android:name="android.permission.INTERNET" />     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />+    <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" />      <!-- Package visibility: without these the deep-link handoff cannot resolve          the official apps and silently falls back to the browser. -->@@ -31,6 +34,15 @@                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>++        <service+            android:name=".notifications.RideTrackingService"+            android:exported="false"+            android:foregroundServiceType="specialUse">+            <property+                android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"+                android:value="ride_tracking" />+        </service>     </application>  </manifest>
taxi/src/main/java/com/vayunmathur/taxi/MainActivity.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/MainActivity.kt b/taxi/src/main/java/com/vayunmathur/taxi/MainActivity.ktindex 4f39ae9cc4..0ea405a545 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/MainActivity.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/MainActivity.kt@@ -1,11 +1,20 @@ package com.vayunmathur.taxi +import android.Manifest+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.mutableStateOf import androidx.compose.ui.res.stringResource+import androidx.core.content.ContextCompat import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle import com.vayunmathur.library.ui.DynamicTheme@@ -17,10 +26,12 @@ import com.vayunmathur.library.util.BottomNavBar import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.NavKey import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.taxi.notifications.RideLiveUpdate import com.vayunmathur.taxi.ui.AccountsScreen import com.vayunmathur.taxi.ui.CurrentRideScreen import com.vayunmathur.taxi.ui.LyftSignInScreen import com.vayunmathur.taxi.ui.RideScreen+import com.vayunmathur.taxi.ui.RideTrackingScreen import kotlinx.serialization.Serializable  sealed interface Route : NavKey {@@ -28,27 +39,61 @@ sealed interface Route : NavKey {     @Serializable data object CurrentRide : Route     @Serializable data object Accounts : Route     @Serializable data object LyftSignIn : Route+    @Serializable data class RideTracking(val rideId: String) : Route }  class MainActivity : ComponentActivity() {+    // The ride 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 trackRideId = mutableStateOf<String?>(null)++    private val requestNotificationPermission =+        registerForActivityResult(ActivityResultContracts.RequestPermission()) { }+     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         NetworkClient.init(this, TrustBundle.STANDARD)         enableEdgeToEdge() +        trackRideId.value = intent.trackRideIdOrNull()+        requestNotificationPermissionIfNeeded()+         setContent {             DynamicTheme {-                TaxiApp()+                TaxiApp(trackRideId)             }         }     }++    override fun onNewIntent(intent: Intent) {+        super.onNewIntent(intent)+        setIntent(intent)+        intent.trackRideIdOrNull()?.let { trackRideId.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.trackRideIdOrNull(): String? =+    getStringExtra(RideLiveUpdate.EXTRA_TRACK_RIDE_ID)?.takeIf { it.isNotBlank() }+ @Composable-private fun TaxiApp() {+private fun TaxiApp(trackRideId: MutableState<String?>) {     val backStack = rememberNavBackStack<Route>(Route.Ride)     val currentPage = backStack.backStack.last() +    // A notification tap deep-links to that ride's tracking screen.+    LaunchedEffect(trackRideId.value) {+        val id = trackRideId.value ?: return@LaunchedEffect+        backStack.add(Route.RideTracking(id))+        trackRideId.value = null+    }+     val pages = listOf(         BottomBarItem(stringResource(R.string.nav_ride), Route.Ride) { IconMap() },         BottomBarItem(stringResource(R.string.nav_current_ride), Route.CurrentRide) { IconNavigationArrow() },@@ -67,5 +112,6 @@ private fun TaxiApp() {             )         }         entry<Route.LyftSignIn> { LyftSignInScreen(onBack = { backStack.pop() }) }+        entry<Route.RideTracking> { route -> RideTrackingScreen(rideId = route.rideId) }     } }
taxi/src/main/java/com/vayunmathur/taxi/notifications/RideLiveUpdate.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/notifications/RideLiveUpdate.kt b/taxi/src/main/java/com/vayunmathur/taxi/notifications/RideLiveUpdate.ktnew file mode 100644index 0000000000..60a2553612--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/notifications/RideLiveUpdate.kt@@ -0,0 +1,123 @@+package com.vayunmathur.taxi.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.library.util.ensureNotificationChannel+import com.vayunmathur.taxi.MainActivity+import com.vayunmathur.taxi.R+import com.vayunmathur.taxi.data.ActiveRide+import com.vayunmathur.taxi.data.RideStatus++/**+ * Builds the ongoing "Live Update" ride-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 RideLiveUpdate {+    const val CHANNEL_ID = "ride_tracking"+    const val NOTIFICATION_ID = 5120+    const val EXTRA_TRACK_RIDE_ID = "com.vayunmathur.taxi.EXTRA_TRACK_RIDE_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 phases the tracker advances through, each with its user-facing label.+    private enum class Milestone(val labelRes: Int) {+        FINDING(R.string.status_finding_driver),+        EN_ROUTE(R.string.status_en_route),+        ARRIVED(R.string.status_arrived),+        ON_TRIP(R.string.status_on_trip),+        COMPLETE(R.string.ride_complete),+    }++    fun ensureChannel(context: Context) {+        context.ensureNotificationChannel(+            id = CHANNEL_ID,+            name = context.getString(R.string.ride_tracking_channel),+            importance = NotificationManager.IMPORTANCE_LOW,+            description = context.getString(R.string.ride_tracking_channel_desc),+        )+    }++    fun build(context: Context, ride: ActiveRide): Notification {+        ensureChannel(context)++        val index = milestoneIndex(ride.status)+        val title = ride.driver?.displayName?.takeIf { it.isNotBlank() }+            ?: ride.vehicle?.description?.takeIf { it.isNotBlank() }+            ?: context.getString(R.string.ride_in_progress)++        val builder = NotificationCompat.Builder(context, CHANNEL_ID)+            .setSmallIcon(R.drawable.ic_launcher_foreground)+            .setContentTitle(title)+            .setContentText(statusText(context, ride, index))+            .setContentIntent(contentIntent(context, ride.rideId))+            .setOngoing(true)+            .setOnlyAlertOnce(true)+            .setCategory(NotificationCompat.CATEGORY_PROGRESS)+            .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)++        if (Build.VERSION.SDK_INT >= LIVE_UPDATE_SDK) {+            val milestones = Milestone.entries+            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(context.getString(milestones[index].labelRes))+            builder.setRequestPromotedOngoing(true)+        } else {+            val max = (Milestone.entries.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, rideId: String?): PendingIntent {+        val intent = Intent(context, MainActivity::class.java).apply {+            flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP+            if (rideId != null) putExtra(EXTRA_TRACK_RIDE_ID, rideId)+        }+        return PendingIntent.getActivity(+            context,+            rideId.hashCode(),+            intent,+            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,+        )+    }++    private fun statusText(context: Context, ride: ActiveRide, index: Int): String {+        val label = context.getString(Milestone.entries[index].labelRes)+        val eta = ride.pickupEtaSeconds+        if (!ride.status.isTerminal && ride.status.isPrePickup && eta != null && eta > 0) {+            val minutes = (eta + 59) / 60+            return context.getString(R.string.notif_status_eta, label, minutes)+        }+        return label+    }++    private fun milestoneIndex(status: RideStatus): Int = when {+        status.isTerminal -> Milestone.COMPLETE.ordinal+        status == RideStatus.PICKED_UP -> Milestone.ON_TRIP.ordinal+        status == RideStatus.ARRIVED -> Milestone.ARRIVED.ordinal+        status == RideStatus.ACCEPTED || status == RideStatus.APPROACHING -> Milestone.EN_ROUTE.ordinal+        else -> Milestone.FINDING.ordinal+    }+}
taxi/src/main/java/com/vayunmathur/taxi/notifications/RideTrackingService.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/notifications/RideTrackingService.kt b/taxi/src/main/java/com/vayunmathur/taxi/notifications/RideTrackingService.ktnew file mode 100644index 0000000000..3310d3c197--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/notifications/RideTrackingService.kt@@ -0,0 +1,175 @@+package com.vayunmathur.taxi.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.taxi.data.ActiveRide+import com.vayunmathur.taxi.data.RideStatus+import com.vayunmathur.taxi.data.RideStatusResult+import com.vayunmathur.taxi.lyft.LyftProvider+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 [RideLiveUpdate] notification current while a ride is+ * in progress, even with the app backgrounded. It polls the same `activeRide()` endpoint+ * the tracking screen uses (falling back to `rideById`), updating every [POLL_MS] until the+ * ride is terminal or gone, then stops itself.+ *+ * Foreground type is `specialUse`: we poll an API on a ride-length timescale, so neither+ * `location` (we read no device location) nor the time-limited `shortService` / `dataSync`+ * types fit.+ */+class RideTrackingService : Service() {+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+    private var pollJob: Job? = null+    private var trackedRideId: String? = null++    override fun onBind(intent: Intent?): IBinder? = null++    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+        val rideId = intent?.getStringExtra(EXTRA_RIDE_ID)+        if (rideId.isNullOrBlank()) {+            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(RideLiveUpdate.build(this, placeholder(rideId)))+        } catch (e: Exception) {+            Log.e(TAG, "startForeground failed", e)+            stopSelf()+            return START_NOT_STICKY+        }++        // Idempotent: a repeat start for the same ride just refreshes, no new loop.+        if (rideId == trackedRideId && pollJob?.isActive == true) {+            return START_REDELIVER_INTENT+        }+        trackedRideId = rideId+        pollJob?.cancel()+        pollJob = scope.launch { pollLoop(rideId) }+        return START_REDELIVER_INTENT+    }++    private suspend fun pollLoop(rideId: String) {+        val provider = LyftProvider(applicationContext)+        while (true) {+            var ended = false+            val ride: ActiveRide? = when (val result = provider.activeRide()) {+                is RideStatusResult.Active -> result.ride+                RideStatusResult.None -> {+                    // The active-ride endpoint may not surface a just-booked ride; read it+                    // directly by id before giving up.+                    val byId = provider.rideById(rideId) as? RideStatusResult.Active+                    if (byId == null) ended = true+                    byId?.ride+                }+                is RideStatusResult.Failed -> {+                    Log.w(TAG, "activeRide failed: ${result.message}")+                    null // transient; keep the last notification and retry+                }+                RideStatusResult.Unsupported -> {+                    ended = true+                    null+                }+            }++            if (ended) {+                Log.d(TAG, "ride $rideId gone; stopping")+                finish()+                return+            }++            if (ride != null) {+                Log.d(TAG, "ride $rideId status=${ride.status} eta=${ride.pickupEtaSeconds}")+                notify(RideLiveUpdate.build(this, ride))+                if (ride.status.isTerminal) {+                    Log.d(TAG, "ride $rideId terminal; 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(RideLiveUpdate.NOTIFICATION_ID, notification)+        } catch (e: SecurityException) {+            Log.w(TAG, "notify skipped (no permission)", e)+        }+    }++    private fun finish() {+        RideLiveUpdate.cancel(this)+        stopForeground(STOP_FOREGROUND_REMOVE)+        stopSelf()+    }++    private fun startForegroundCompat(notification: Notification) {+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+            startForeground(+                RideLiveUpdate.NOTIFICATION_ID,+                notification,+                ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE,+            )+        } else {+            startForeground(RideLiveUpdate.NOTIFICATION_ID, notification)+        }+    }++    private fun placeholder(rideId: String) = ActiveRide(+        rideId = rideId,+        status = RideStatus.UNKNOWN,+        statusRaw = null,+        driver = null,+        vehicle = null,+        driverLocation = null,+        stops = emptyList(),+        raw = "",+    )++    override fun onDestroy() {+        scope.cancel()+        super.onDestroy()+    }++    companion object {+        private const val TAG = "RideTrackingService"++        /** Mirrors RideTrackingScreen's active-ride poll cadence. */+        private const val POLL_MS = 5_000L+        private const val TERMINAL_LINGER_MS = 5_000L+        private const val EXTRA_RIDE_ID = "ride_id"++        fun start(context: Context, rideId: String?) {+            if (rideId.isNullOrBlank()) return+            val intent = Intent(context, RideTrackingService::class.java)+                .putExtra(EXTRA_RIDE_ID, rideId)+            context.startForegroundService(intent)+        }++        fun stop(context: Context) {+            context.stopService(Intent(context, RideTrackingService::class.java))+        }+    }+}
taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.kt b/taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.ktindex ee6519be61..5a1ee78052 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/ui/LyftBooking.kt@@ -38,6 +38,7 @@ import com.vayunmathur.taxi.data.PaymentMethodsResult import com.vayunmathur.taxi.data.Place import com.vayunmathur.taxi.data.RideQuote import com.vayunmathur.taxi.lyft.LyftProvider+import com.vayunmathur.taxi.notifications.RideTrackingService import kotlinx.coroutines.launch  /** Everything the Lyft booking flow needs, gathered when the user taps a Lyft fare. */@@ -110,7 +111,11 @@ fun LyftBookingFlow(                 )             ) {                 is BookingResult.DryRun -> Step.DryRun(result.requestJson)-                is BookingResult.Created -> Step.Created(result.rideId, result.status, result.raw)+                is BookingResult.Created -> {+                    // Kick off the background Live Update tracker for the new ride.+                    RideTrackingService.start(context, result.rideId)+                    Step.Created(result.rideId, result.status, result.raw)+                }                 is BookingResult.Failed -> Step.Failed(result.message)                 BookingResult.Unsupported ->                     Step.Failed(context.getString(R.string.booking_no_payment))
taxi/src/main/java/com/vayunmathur/taxi/ui/RideTrackingScreen.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/ui/RideTrackingScreen.kt b/taxi/src/main/java/com/vayunmathur/taxi/ui/RideTrackingScreen.ktindex 117fe98c12..5bdfa60a26 100644--- a/taxi/src/main/java/com/vayunmathur/taxi/ui/RideTrackingScreen.kt+++ b/taxi/src/main/java/com/vayunmathur/taxi/ui/RideTrackingScreen.kt@@ -66,6 +66,7 @@ import com.vayunmathur.taxi.data.RideStatus import com.vayunmathur.taxi.data.RideStatusResult import com.vayunmathur.taxi.data.RideStopInfo import com.vayunmathur.taxi.lyft.LyftProvider+import com.vayunmathur.taxi.notifications.RideTrackingService import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlin.math.max@@ -143,6 +144,9 @@ fun RideTrackingScreen(rideId: String) {      // Active-ride poll: status, driver/vehicle details, per-stop ETA.     LaunchedEffect(rideId) {+        // Keep the background Live Update tracker running for this ride too, so tracking+        // opened from the Current ride tab (or a re-opened app) is covered. Idempotent.+        RideTrackingService.start(context, rideId)         while (true) {             when (val result = provider.activeRide()) {                 is RideStatusResult.Active -> {
taxi/src/main/res/values/strings.xml
diff --git a/taxi/src/main/res/values/strings.xml b/taxi/src/main/res/values/strings.xmlindex ee3a1d4a59..cd53a6aed3 100644--- a/taxi/src/main/res/values/strings.xml+++ b/taxi/src/main/res/values/strings.xml@@ -125,6 +125,12 @@     <string name="status_finding_driver">Finding your driver</string>     <string name="ride_complete">Ride complete</string> +    <!-- Live Update notification -->+    <string name="ride_tracking_channel">Ride tracking</string>+    <string name="ride_tracking_channel_desc">Ongoing updates while your ride is in progress</string>+    <!-- %1$s = status label e.g. Driver is on the way, %2$d = minutes remaining -->+    <string name="notif_status_eta">%1$s · %2$d min</string>+     <!-- Account -->     <string name="sign_out">Sign out</string>     <string name="sign_out_title">Sign out of Lyft?</string>