maps P12: Android Auto navigation (Car App Library + existing routing/nav)
- Commit
fabbfb0f35ab4de9089792a6095ed99fe0e59950- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-17 01:02 UTC (3 months ago)
- Parents
f210ea6
Diff
maps/build.gradle.kts
diff --git a/maps/build.gradle.kts b/maps/build.gradle.ktsindex 9eea87ad9c..a46dafa7a0 100644--- a/maps/build.gradle.kts+++ b/maps/build.gradle.kts@@ -38,4 +38,12 @@ dependencies { implementation(libs.flatgeobuf) implementation(project(":library:downloadservice"))++ // Android Auto (P12): AndroidX Car App Library. `app` provides the+ // CarAppService/Session/Screen/template model; `app-projected` provides the+ // phone-projected (Android Auto) host connection. Coordinates are declared+ // inline (rather than via the version catalog) to keep this phase confined+ // to maps/. Only pulled into the car code path — the phone UI is untouched.+ implementation("androidx.car.app:app:1.4.0")+ implementation("androidx.car.app:app-projected:1.4.0") }
maps/src/main/AndroidManifest.xml
diff --git a/maps/src/main/AndroidManifest.xml b/maps/src/main/AndroidManifest.xmlindex 4822ffe1c2..9a701537d7 100644--- a/maps/src/main/AndroidManifest.xml+++ b/maps/src/main/AndroidManifest.xml@@ -55,6 +55,33 @@ android:name=".util.NavigationService" android:foregroundServiceType="location" android:exported="false" />++ <!-- Android Auto (P12): the Car App Library entry point. The host+ (Android Auto, projected) binds this CarAppService via the+ androidx.car.app.CarAppService action; the NAVIGATION category+ marks it as a turn-by-turn navigation app so it may draw to the+ car Surface and use the NavigationTemplate. The map/nav session+ reuses the existing routing + NavigationSessionManager + system+ TTS stack; the phone UI (MainActivity) is unaffected. -->+ <service+ android:name=".car.MapsCarAppService"+ android:exported="true"+ android:foregroundServiceType="location">+ <intent-filter>+ <action android:name="androidx.car.app.CarAppService" />+ <category android:name="androidx.car.app.category.NAVIGATION" />+ </intent-filter>+ </service>++ <!-- Minimum Car App API level this app targets (Car App Library). -->+ <meta-data+ android:name="androidx.car.app.minCarApiLevel"+ android:value="1" />++ <!-- Declares this app to the Android Auto host as a template app. -->+ <meta-data+ android:name="com.google.android.gms.car.application"+ android:resource="@xml/automotive_app_desc" /> </application> </manifest>\ No newline at end of file
maps/src/main/java/com/vayunmathur/maps/car/CarManeuvers.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/car/CarManeuvers.kt b/maps/src/main/java/com/vayunmathur/maps/car/CarManeuvers.ktnew file mode 100644index 0000000000..33863fa7c2--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/car/CarManeuvers.kt@@ -0,0 +1,82 @@+package com.vayunmathur.maps.car++import androidx.car.app.navigation.model.Lane+import androidx.car.app.navigation.model.LaneDirection+import androidx.car.app.navigation.model.Maneuver+import com.vayunmathur.maps.util.RouteService++/**+ * Maps the existing routing model ([RouteService.API.Maneuver] / lane data+ * emitted by the Rust [com.vayunmathur.maps.util.OfflineRouter]) onto the+ * AndroidX Car App Library's navigation model.+ *+ * The car host renders a built-in icon for each [Maneuver] type, so we only+ * need to pick the closest matching `TYPE_*`; no bitmap resources are required.+ * Lane guidance is translated from [RouteService.API.Lane] (P5a) where present.+ */+internal object CarManeuvers {++ /** Translate a routing maneuver into a Car App Library [Maneuver] type. */+ fun typeFor(maneuver: RouteService.API.Maneuver): Int = when (maneuver) {+ RouteService.API.Maneuver.DEPART -> Maneuver.TYPE_DEPART+ RouteService.API.Maneuver.NAME_CHANGE -> Maneuver.TYPE_NAME_CHANGE+ RouteService.API.Maneuver.STRAIGHT -> Maneuver.TYPE_STRAIGHT+ RouteService.API.Maneuver.TURN_SLIGHT_LEFT -> Maneuver.TYPE_TURN_SLIGHT_LEFT+ RouteService.API.Maneuver.TURN_SLIGHT_RIGHT -> Maneuver.TYPE_TURN_SLIGHT_RIGHT+ RouteService.API.Maneuver.TURN_LEFT -> Maneuver.TYPE_TURN_NORMAL_LEFT+ RouteService.API.Maneuver.TURN_RIGHT -> Maneuver.TYPE_TURN_NORMAL_RIGHT+ RouteService.API.Maneuver.TURN_SHARP_LEFT -> Maneuver.TYPE_TURN_SHARP_LEFT+ RouteService.API.Maneuver.TURN_SHARP_RIGHT -> Maneuver.TYPE_TURN_SHARP_RIGHT+ RouteService.API.Maneuver.UTURN_LEFT -> Maneuver.TYPE_U_TURN_LEFT+ RouteService.API.Maneuver.UTURN_RIGHT -> Maneuver.TYPE_U_TURN_RIGHT+ RouteService.API.Maneuver.RAMP_LEFT -> Maneuver.TYPE_ON_RAMP_NORMAL_LEFT+ RouteService.API.Maneuver.RAMP_RIGHT -> Maneuver.TYPE_ON_RAMP_NORMAL_RIGHT+ RouteService.API.Maneuver.FORK_LEFT -> Maneuver.TYPE_FORK_LEFT+ RouteService.API.Maneuver.FORK_RIGHT -> Maneuver.TYPE_FORK_RIGHT+ RouteService.API.Maneuver.MERGE -> Maneuver.TYPE_MERGE_SIDE_UNSPECIFIED+ RouteService.API.Maneuver.ROUNDABOUT_LEFT -> Maneuver.TYPE_ROUNDABOUT_ENTER_CCW+ RouteService.API.Maneuver.ROUNDABOUT_RIGHT -> Maneuver.TYPE_ROUNDABOUT_ENTER_CW+ RouteService.API.Maneuver.FERRY -> Maneuver.TYPE_FERRY_BOAT+ RouteService.API.Maneuver.FERRY_TRAIN -> Maneuver.TYPE_FERRY_TRAIN+ // WAIT / RIDE are transit-only and never surface in a DRIVE session;+ // fall back to a neutral "continue" glyph.+ RouteService.API.Maneuver.WAIT,+ RouteService.API.Maneuver.RIDE,+ RouteService.API.Maneuver.MANEUVER_UNSPECIFIED -> Maneuver.TYPE_STRAIGHT+ }++ /** Build a Car App Library [Maneuver] for a routing maneuver. */+ fun build(maneuver: RouteService.API.Maneuver): Maneuver =+ Maneuver.Builder(typeFor(maneuver)).build()++ /** Lane-arrow shape for a routing maneuver (P5a lane guidance). */+ private fun laneShapeFor(maneuver: RouteService.API.Maneuver): Int = when (maneuver) {+ RouteService.API.Maneuver.TURN_SLIGHT_LEFT,+ RouteService.API.Maneuver.FORK_LEFT,+ RouteService.API.Maneuver.RAMP_LEFT -> LaneDirection.SHAPE_SLIGHT_LEFT+ RouteService.API.Maneuver.TURN_SLIGHT_RIGHT,+ RouteService.API.Maneuver.FORK_RIGHT,+ RouteService.API.Maneuver.RAMP_RIGHT -> LaneDirection.SHAPE_SLIGHT_RIGHT+ RouteService.API.Maneuver.TURN_LEFT,+ RouteService.API.Maneuver.ROUNDABOUT_LEFT -> LaneDirection.SHAPE_NORMAL_LEFT+ RouteService.API.Maneuver.TURN_RIGHT,+ RouteService.API.Maneuver.ROUNDABOUT_RIGHT -> LaneDirection.SHAPE_NORMAL_RIGHT+ RouteService.API.Maneuver.TURN_SHARP_LEFT -> LaneDirection.SHAPE_SHARP_LEFT+ RouteService.API.Maneuver.TURN_SHARP_RIGHT -> LaneDirection.SHAPE_SHARP_RIGHT+ RouteService.API.Maneuver.UTURN_LEFT -> LaneDirection.SHAPE_U_TURN_LEFT+ RouteService.API.Maneuver.UTURN_RIGHT -> LaneDirection.SHAPE_U_TURN_RIGHT+ else -> LaneDirection.SHAPE_STRAIGHT+ }++ /** Translate the router's per-junction lanes into Car App Library [Lane]s. */+ fun lanes(source: List<RouteService.API.Lane>): List<Lane> = source.map { lane ->+ val builder = Lane.Builder()+ val directions = lane.directions.ifEmpty {+ listOf(RouteService.API.Maneuver.STRAIGHT)+ }+ for (dir in directions) {+ builder.addDirection(LaneDirection.create(laneShapeFor(dir), lane.active))+ }+ builder.build()+ }+}
maps/src/main/java/com/vayunmathur/maps/car/CarMapRenderer.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/car/CarMapRenderer.kt b/maps/src/main/java/com/vayunmathur/maps/car/CarMapRenderer.ktnew file mode 100644index 0000000000..1ba1b91556--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/car/CarMapRenderer.kt@@ -0,0 +1,315 @@+package com.vayunmathur.maps.car++import android.content.Context+import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.Color+import android.graphics.Paint+import android.graphics.Path+import android.graphics.PointF+import android.graphics.Rect+import android.os.Handler+import android.os.Looper+import android.util.Log+import android.view.Surface+import androidx.car.app.CarContext+import androidx.car.app.SurfaceCallback+import androidx.car.app.SurfaceContainer+import com.vayunmathur.maps.ui.patchStyleForHybrid+import com.vayunmathur.maps.util.MapTileCache+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import org.maplibre.android.MapLibre+import org.maplibre.android.camera.CameraPosition+import org.maplibre.android.geometry.LatLng+import org.maplibre.android.snapshotter.MapSnapshot+import org.maplibre.android.snapshotter.MapSnapshotter+import org.maplibre.spatialk.geojson.Position++/**+ * Renders the maps basemap onto the Android Auto car [Surface] (P12).+ *+ * `maplibre-compose` is a declarative, phone-only Compose wrapper and cannot+ * draw into an arbitrary car [Surface]. Instead we drive the **prebuilt** native+ * MapLibre Android SDK (`org.maplibre.android`, pulled in transitively by+ * maplibre-compose — prebuilt native is allowed, no hand-authored C++) via its+ * [MapSnapshotter]: for each frame we render the same patched `style.json` the+ * phone map uses off-screen to a [Bitmap], overlay the route line + puck onto+ * the bitmap (projected with [MapSnapshot.pixelForLatLng]), and blit it to the+ * car surface. This reuses the app's existing tile stack: [MapTileCache]+ * installs the `library:network` HTTP module so the snapshotter streams the same+ * pmtiles basemap as the phone.+ *+ * Frames are produced on demand — when the camera follows a new GPS fix+ * ([setCamera]) or the route/puck changes — not on a continuous render loop, so+ * a parked or stationary car costs nothing.+ *+ * All snapshotter interaction happens on the main thread (the snapshotter needs+ * a Looper and its callbacks return on the thread that started it); the+ * [SurfaceCallback] entry points are already invoked on the main thread and+ * [setCamera]/[setRoute]/[setPuck] marshal onto [mainHandler].+ */+internal class CarMapRenderer(+ private val carContext: CarContext,+ private val darkMap: Boolean = false,+) : SurfaceCallback {++ private val mainHandler = Handler(Looper.getMainLooper())+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)++ private var surface: Surface? = null+ private var surfaceWidth = 0+ private var surfaceHeight = 0+ private var pixelRatio = 1f++ private var snapshotter: MapSnapshotter? = null+ private var styleJson: String? = null++ // Camera + overlay state (main-thread only).+ private var cameraTarget: Position? = null+ private var cameraZoom = 15.0+ private var cameraBearing = 0.0+ private var cameraTilt = 0.0+ private var routePolyline: List<Position> = emptyList()+ private var puck: Position? = null++ private var rendering = false+ private var dirty = false++ // ---- Paints for the route/puck overlay ----+ private val routeCasingPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ style = Paint.Style.STROKE+ color = Color.WHITE+ strokeWidth = 18f+ strokeCap = Paint.Cap.ROUND+ strokeJoin = Paint.Join.ROUND+ }+ private val routePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ style = Paint.Style.STROKE+ color = Color.parseColor("#1A73E8")+ strokeWidth = 12f+ strokeCap = Paint.Cap.ROUND+ strokeJoin = Paint.Join.ROUND+ }+ private val puckPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ style = Paint.Style.FILL+ color = Color.parseColor("#1A73E8")+ }+ private val puckCasingPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ style = Paint.Style.FILL+ color = Color.WHITE+ }++ // ----------------------------------------------------------------+ // SurfaceCallback+ // ----------------------------------------------------------------++ override fun onSurfaceAvailable(surfaceContainer: SurfaceContainer) {+ Log.i(TAG, "onSurfaceAvailable ${surfaceContainer.width}x${surfaceContainer.height}")+ surface = surfaceContainer.getSurface()+ surfaceWidth = surfaceContainer.width+ surfaceHeight = surfaceContainer.height+ pixelRatio = (surfaceContainer.dpi / 160f).coerceAtLeast(1f)+ ensureStyleAndSnapshotter()+ }++ override fun onSurfaceDestroyed(surfaceContainer: SurfaceContainer) {+ Log.i(TAG, "onSurfaceDestroyed")+ surface = null+ snapshotter?.cancel()+ }++ // ----------------------------------------------------------------+ // Public drive API (safe to call from any thread)+ // ----------------------------------------------------------------++ fun setCamera(target: Position, zoom: Double, bearing: Double, tilt: Double) = onMain {+ cameraTarget = target+ cameraZoom = zoom+ cameraBearing = bearing+ cameraTilt = tilt+ requestRender()+ }++ fun setRoute(polyline: List<Position>) = onMain {+ routePolyline = polyline+ requestRender()+ }++ fun setPuck(position: Position?) = onMain {+ puck = position+ requestRender()+ }++ fun destroy() = onMain {+ snapshotter?.cancel()+ snapshotter = null+ surface = null+ scope.cancel()+ }++ // ----------------------------------------------------------------+ // Snapshotter setup + render loop (main thread)+ // ----------------------------------------------------------------++ private fun ensureStyleAndSnapshotter() {+ if (surface == null || surfaceWidth <= 0 || surfaceHeight <= 0) return+ // Init the native SDK + our caching HTTP stack once; both are idempotent.+ MapLibre.getInstance(carContext)+ MapTileCache.install(carContext)++ if (styleJson == null) {+ scope.launch {+ val json = withContext(Dispatchers.IO) {+ val raw = carContext.assets.open("style.json").bufferedReader().readText()+ // Stream the same pmtiles basemap the phone uses (both the+ // base and hybrid sources point at the streamed URL — the+ // car app doesn't select downloaded offline zones).+ patchStyleForHybrid(+ raw,+ MapTileCache.BASEMAP_PMTILES_URL,+ MapTileCache.BASEMAP_PMTILES_URL,+ darkMap,+ )+ }+ styleJson = json+ createSnapshotter()+ requestRender()+ }+ } else if (snapshotter == null) {+ createSnapshotter()+ requestRender()+ } else {+ requestRender()+ }+ }++ private fun createSnapshotter() {+ val json = styleJson ?: return+ if (surfaceWidth <= 0 || surfaceHeight <= 0) return+ snapshotter?.cancel()+ val options = MapSnapshotter.Options(surfaceWidth, surfaceHeight)+ .withStyleBuilder(org.maplibre.android.maps.Style.Builder().fromJson(json))+ .withPixelRatio(pixelRatio)+ .withLogo(false)+ options.showAttribution = false+ snapshotter = MapSnapshotter(carContext, options)+ }++ private fun requestRender() {+ val snap = snapshotter ?: return+ val target = cameraTarget ?: return+ if (surface?.isValid != true) return+ if (rendering) {+ dirty = true+ return+ }+ rendering = true+ dirty = false++ snap.setSize(surfaceWidth, surfaceHeight)+ snap.setCameraPosition(+ CameraPosition.Builder()+ .target(LatLng(target.latitude, target.longitude))+ .zoom(cameraZoom)+ .bearing(cameraBearing)+ .tilt(cameraTilt)+ .build()+ )+ snap.start(+ { result -> onSnapshotReady(result) },+ { error -> onSnapshotError(error) },+ )+ }++ private fun onSnapshotError(error: String?) {+ Log.w(TAG, "snapshot error: $error")+ rendering = false+ if (dirty) requestRender()+ }++ private fun onSnapshotReady(result: MapSnapshot) {+ rendering = false+ val surface = this.surface+ if (surface != null && surface.isValid) {+ val bitmap = result.bitmap+ drawOverlay(bitmap, result)+ blitToSurface(surface, bitmap)+ }+ if (dirty) requestRender()+ }++ /** Draw the route line + puck onto the snapshot bitmap (bitmap pixel space). */+ private fun drawOverlay(bitmap: Bitmap, snapshot: MapSnapshot) {+ val canvas = Canvas(bitmap)++ val poly = routePolyline+ if (poly.size >= 2) {+ val path = Path()+ var started = false+ for (p in poly) {+ val pt: PointF = snapshot.pixelForLatLng(LatLng(p.latitude, p.longitude))+ if (!started) {+ path.moveTo(pt.x, pt.y)+ started = true+ } else {+ path.lineTo(pt.x, pt.y)+ }+ }+ canvas.drawPath(path, routeCasingPaint)+ canvas.drawPath(path, routePaint)+ }++ puck?.let { p ->+ val pt = snapshot.pixelForLatLng(LatLng(p.latitude, p.longitude))+ drawPuck(canvas, pt.x, pt.y)+ }+ }++ /**+ * Draw a north-pointing chevron for the puck. During navigation the camera+ * bearing tracks the course-over-ground, so "up" on screen is the direction+ * of travel and a fixed up-arrow reads correctly.+ */+ private fun drawPuck(canvas: Canvas, cx: Float, cy: Float) {+ val r = 22f+ canvas.drawCircle(cx, cy, r + 4f, puckCasingPaint)+ val arrow = Path().apply {+ moveTo(cx, cy - r)+ lineTo(cx - r * 0.7f, cy + r * 0.7f)+ lineTo(cx, cy + r * 0.35f)+ lineTo(cx + r * 0.7f, cy + r * 0.7f)+ close()+ }+ canvas.drawPath(arrow, puckPaint)+ }++ private fun blitToSurface(surface: Surface, bitmap: Bitmap) {+ val canvas: Canvas = try {+ surface.lockCanvas(null)+ } catch (e: Exception) {+ Log.w(TAG, "lockCanvas failed", e)+ return+ }+ try {+ val dst = Rect(0, 0, surfaceWidth, surfaceHeight)+ canvas.drawColor(Color.BLACK)+ canvas.drawBitmap(bitmap, null, dst, null)+ } finally {+ runCatching { surface.unlockCanvasAndPost(canvas) }+ }+ }++ private inline fun onMain(crossinline block: () -> Unit) {+ if (Looper.myLooper() == Looper.getMainLooper()) block()+ else mainHandler.post { block() }+ }++ private companion object {+ const val TAG = "CarMapRenderer"+ }+}
maps/src/main/java/com/vayunmathur/maps/car/CarSearchScreen.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/car/CarSearchScreen.kt b/maps/src/main/java/com/vayunmathur/maps/car/CarSearchScreen.ktnew file mode 100644index 0000000000..45ded89ba3--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/car/CarSearchScreen.kt@@ -0,0 +1,260 @@+package com.vayunmathur.maps.car++import android.Manifest+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.location.Location+import android.location.LocationManager+import android.os.Bundle+import android.speech.RecognitionListener+import android.speech.RecognizerIntent+import android.speech.SpeechRecognizer+import androidx.car.app.CarContext+import androidx.car.app.Screen+import androidx.car.app.model.Action+import androidx.car.app.model.ActionStrip+import androidx.car.app.model.CarLocation+import androidx.car.app.model.Header+import androidx.car.app.model.ItemList+import androidx.car.app.model.Metadata+import androidx.car.app.model.Place+import androidx.car.app.model.Row+import androidx.car.app.model.Template+import androidx.car.app.navigation.model.PlaceListNavigationTemplate+import androidx.core.content.ContextCompat+import androidx.lifecycle.DefaultLifecycleObserver+import androidx.lifecycle.LifecycleOwner+import com.vayunmathur.maps.R+import com.vayunmathur.maps.data.SpecificFeature+import com.vayunmathur.maps.data.google.GoogleSearchDataSource+import com.vayunmathur.maps.data.google.GoogleSearchResult+import com.vayunmathur.maps.util.NavigationService+import com.vayunmathur.maps.util.NavigationSessionManager+import com.vayunmathur.maps.util.OfflineRouter+import com.vayunmathur.maps.util.RouteService+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import org.maplibre.spatialk.geojson.Position++/**+ * Android Auto search screen (P12).+ *+ * Voice-first: the Search action launches the **system** [SpeechRecognizer]+ * (the OS routes it to the user-selected recognition service — the same+ * system-STT path P8 uses on the phone via `VoiceSearchButton`), and the final+ * transcript is fed to the existing keyless [GoogleSearchDataSource] (P3). Hits+ * are shown in a [PlaceListNavigationTemplate] (list + map markers); tapping a+ * result routes to it with the existing [OfflineRouter], starts the shared+ * [NavigationSessionManager] + [NavigationService], and returns to the map+ * screen where turn-by-turn takes over.+ */+class CarSearchScreen(carContext: CarContext) : Screen(carContext) {++ private var results: List<GoogleSearchResult> = emptyList()+ private var loading = false+ private var message: String? = null+ private var recognizer: SpeechRecognizer? = null+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)++ init {+ message = carContext.getString(R.string.car_voice_hint)+ lifecycle.addObserver(object : DefaultLifecycleObserver {+ override fun onDestroy(owner: LifecycleOwner) {+ runCatching { recognizer?.destroy() }+ recognizer = null+ scope.cancel()+ }+ })+ }++ override fun onGetTemplate(): Template {+ val builder = PlaceListNavigationTemplate.Builder()+ .setHeader(+ Header.Builder()+ .setStartHeaderAction(Action.BACK)+ .setTitle(carContext.getString(R.string.car_search_title))+ .build()+ )+ .setActionStrip(+ ActionStrip.Builder()+ .addAction(+ Action.Builder()+ .setTitle(carContext.getString(R.string.car_search_action))+ .setOnClickListener { requestMicThenListen() }+ .build()+ )+ .build()+ )+ if (loading) {+ builder.setLoading(true)+ } else {+ builder.setItemList(buildItemList())+ }+ return builder.build()+ }++ private fun buildItemList(): ItemList {+ val ib = ItemList.Builder()+ if (results.isEmpty()) {+ ib.setNoItemsMessage(+ message ?: carContext.getString(R.string.car_no_results)+ )+ } else {+ for (r in results) {+ val row = Row.Builder().setTitle(r.name)+ val subtitle = r.address ?: r.category+ if (!subtitle.isNullOrBlank()) row.addText(subtitle)+ row.setMetadata(+ Metadata.Builder()+ .setPlace(Place.Builder(CarLocation.create(r.lat, r.lng)).build())+ .build()+ )+ row.setOnClickListener { startNavigationTo(r) }+ ib.addItem(row.build())+ }+ }+ return ib.build()+ }++ // ----------------------------------------------------------------+ // System STT+ // ----------------------------------------------------------------++ private fun requestMicThenListen() {+ val granted = ContextCompat.checkSelfPermission(+ carContext, Manifest.permission.RECORD_AUDIO+ ) == PackageManager.PERMISSION_GRANTED+ if (granted) {+ startListening()+ } else {+ runCatching {+ carContext.requestPermissions(+ listOf(Manifest.permission.RECORD_AUDIO)+ ) { grantedList, _ ->+ if (Manifest.permission.RECORD_AUDIO in grantedList) startListening()+ }+ }+ }+ }++ private fun startListening() {+ if (!SpeechRecognizer.isRecognitionAvailable(carContext)) return+ val sr = recognizer ?: SpeechRecognizer.createSpeechRecognizer(carContext)+ .also { recognizer = it }+ sr.setRecognitionListener(object : RecognitionListener {+ override fun onResults(bundle: Bundle?) {+ bundle?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)+ ?.firstOrNull()+ ?.takeIf { it.isNotBlank() }+ ?.let { runSearch(it) }+ }++ override fun onReadyForSpeech(params: Bundle?) {}+ override fun onBeginningOfSpeech() {}+ override fun onRmsChanged(rmsdB: Float) {}+ override fun onBufferReceived(buffer: ByteArray?) {}+ override fun onEndOfSpeech() {}+ override fun onError(error: Int) {}+ override fun onPartialResults(partialResults: Bundle?) {}+ override fun onEvent(eventType: Int, params: Bundle?) {}+ })+ val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {+ putExtra(+ RecognizerIntent.EXTRA_LANGUAGE_MODEL,+ RecognizerIntent.LANGUAGE_MODEL_FREE_FORM,+ )+ putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1)+ }+ runCatching { sr.startListening(intent) }+ }++ // ----------------------------------------------------------------+ // Search + routing (existing stack)+ // ----------------------------------------------------------------++ private fun runSearch(query: String) {+ val near = lastKnownPosition()+ loading = true+ message = carContext.getString(R.string.car_searching)+ invalidate()+ scope.launch {+ val hits = GoogleSearchDataSource.search(+ query,+ near?.latitude ?: 0.0,+ near?.longitude ?: 0.0,+ )+ results = hits+ loading = false+ message = if (hits.isEmpty()) {+ carContext.getString(R.string.car_no_results)+ } else null+ invalidate()+ }+ }++ private fun startNavigationTo(result: GoogleSearchResult) {+ val userPos = lastKnownPosition()+ if (userPos == null) {+ message = carContext.getString(R.string.car_route_failed)+ invalidate()+ return+ }+ loading = true+ invalidate()+ scope.launch {+ val dest = Position(longitude = result.lng, latitude = result.lat)+ val routeFeature = SpecificFeature.Route(+ listOf(+ null, // first waypoint = current position (getRouteMulti fills it)+ SpecificFeature.GenericPlace(+ name = result.name,+ phone = null,+ website = null,+ openingHours = null,+ position = dest,+ ),+ )+ )+ val route = OfflineRouter.getRouteMulti(+ carContext, routeFeature, userPos, RouteService.TravelMode.DRIVE+ )+ if (route == null) {+ loading = false+ message = carContext.getString(R.string.car_route_failed)+ invalidate()+ return@launch+ }+ carContext.startForegroundService(+ Intent(carContext, NavigationService::class.java)+ )+ NavigationSessionManager.init(carContext)+ NavigationSessionManager.start(+ route = route,+ mode = RouteService.TravelMode.DRIVE,+ destination = dest,+ destinationLabel = result.name,+ )+ // Back to the map; NavMapScreen observes the session and shows+ // turn-by-turn.+ screenManager.pop()+ }+ }++ private fun lastKnownPosition(): Position? {+ if (ContextCompat.checkSelfPermission(+ carContext, Manifest.permission.ACCESS_FINE_LOCATION+ ) != PackageManager.PERMISSION_GRANTED+ ) return null+ val lm = carContext.getSystemService(Context.LOCATION_SERVICE) as? LocationManager+ ?: return null+ val loc: Location? = runCatching {+ lm.getLastKnownLocation(LocationManager.GPS_PROVIDER)+ ?: lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)+ }.getOrNull()+ return loc?.let { Position(longitude = it.longitude, latitude = it.latitude) }+ }+}
maps/src/main/java/com/vayunmathur/maps/car/MapsCarAppService.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/car/MapsCarAppService.kt b/maps/src/main/java/com/vayunmathur/maps/car/MapsCarAppService.ktnew file mode 100644index 0000000000..1898672e4f--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/car/MapsCarAppService.kt@@ -0,0 +1,26 @@+package com.vayunmathur.maps.car++import androidx.car.app.CarAppService+import androidx.car.app.Session+import androidx.car.app.validation.HostValidator++/**+ * Android Auto entry point (P12).+ *+ * Declared in the manifest with the `androidx.car.app.CarAppService` action and+ * the `androidx.car.app.category.NAVIGATION` category, so the Android Auto host+ * treats this as a turn-by-turn navigation app (map surface + NavigationTemplate).+ * All routing, the navigation session/progress, and voice guidance are the+ * app's existing phone stack — see [MapsSession].+ */+class MapsCarAppService : CarAppService() {++ // Dev posture: accept any host. Before shipping this must be tightened to a+ // real allow-list (Android Auto / Automotive OS signatures) via+ // HostValidator.Builder + the car-app allowlist — that is part of the+ // on-device (DHU/car) verification follow-up, not compile-time.+ override fun createHostValidator(): HostValidator =+ HostValidator.ALLOW_ALL_HOSTS_VALIDATOR++ override fun onCreateSession(): Session = MapsSession()+}
maps/src/main/java/com/vayunmathur/maps/car/MapsSession.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/car/MapsSession.kt b/maps/src/main/java/com/vayunmathur/maps/car/MapsSession.ktnew file mode 100644index 0000000000..6810da1001--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/car/MapsSession.kt@@ -0,0 +1,91 @@+package com.vayunmathur.maps.car++import android.Manifest+import android.content.Intent+import android.util.Log+import androidx.car.app.Screen+import androidx.car.app.Session+import androidx.car.app.navigation.NavigationManager+import androidx.car.app.navigation.NavigationManagerCallback+import androidx.lifecycle.DefaultLifecycleObserver+import androidx.lifecycle.LifecycleOwner+import com.vayunmathur.maps.util.NavigationService+import com.vayunmathur.maps.util.NavigationSessionManager+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch++/**+ * The Car App Library [Session] for the maps navigation app (P12).+ *+ * Owns the single [NavMapScreen] and bridges the existing process-global+ * [NavigationSessionManager] to the car host's [NavigationManager]:+ * - reports navigation start/stop to the host (so the car shows we're the+ * active nav app and can surface a "stop" affordance);+ * - handles the host's "stop navigation" request by tearing down the existing+ * foreground [NavigationService], which stops the session everywhere (phone+ * + car share the same singleton).+ */+class MapsSession : Session() {++ private var navRunning = false+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)++ override fun onCreateScreen(intent: Intent): Screen {+ NavigationSessionManager.init(carContext)++ lifecycle.addObserver(object : DefaultLifecycleObserver {+ override fun onDestroy(owner: LifecycleOwner) {+ scope.cancel()+ }+ })++ // Location is needed both to draw the puck and to route from the current+ // position. Best-effort request; the screen still renders without it.+ runCatching {+ carContext.requestPermissions(+ listOf(Manifest.permission.ACCESS_FINE_LOCATION)+ ) { _, _ -> }+ }++ val navigationManager = carContext.getCarService(NavigationManager::class.java)+ navigationManager.setNavigationManagerCallback(object : NavigationManagerCallback {+ override fun onStopNavigation() {+ // Host asked us to stop (e.g. another nav app took over). Route+ // it through the existing service so all observers reset.+ stopExistingNavigation()+ }+ })++ // Mirror the existing session state into the host's NavigationManager.+ scope.launch {+ NavigationSessionManager.state.collect { state ->+ val active = state !is NavigationSessionManager.NavState.Idle &&+ state !is NavigationSessionManager.NavState.Failed+ if (active && !navRunning) {+ runCatching { navigationManager.navigationStarted() }+ navRunning = true+ } else if (!active && navRunning) {+ runCatching { navigationManager.navigationEnded() }+ navRunning = false+ }+ }+ }++ return NavMapScreen(carContext)+ }++ private fun stopExistingNavigation() {+ runCatching {+ val intent = Intent(carContext, NavigationService::class.java)+ .apply { action = NavigationService.ACTION_STOP }+ carContext.startService(intent)+ }.onFailure { Log.w(TAG, "stopExistingNavigation failed", it) }+ }++ private companion object {+ const val TAG = "MapsSession"+ }+}
maps/src/main/java/com/vayunmathur/maps/car/NavMapScreen.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/car/NavMapScreen.kt b/maps/src/main/java/com/vayunmathur/maps/car/NavMapScreen.ktnew file mode 100644index 0000000000..738d8406e6--- /dev/null+++ b/maps/src/main/java/com/vayunmathur/maps/car/NavMapScreen.kt@@ -0,0 +1,230 @@+package com.vayunmathur.maps.car++import android.Manifest+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.location.Location+import android.location.LocationManager+import androidx.car.app.AppManager+import androidx.car.app.CarContext+import androidx.car.app.Screen+import androidx.car.app.model.Action+import androidx.car.app.model.ActionStrip+import androidx.car.app.model.DateTimeWithZone+import androidx.car.app.model.Distance+import androidx.car.app.model.Template+import androidx.car.app.navigation.model.Maneuver+import androidx.car.app.navigation.model.NavigationTemplate+import androidx.car.app.navigation.model.RoutingInfo+import androidx.car.app.navigation.model.Step+import androidx.car.app.navigation.model.TravelEstimate+import androidx.core.content.ContextCompat+import androidx.lifecycle.DefaultLifecycleObserver+import androidx.lifecycle.LifecycleOwner+import com.vayunmathur.maps.R+import com.vayunmathur.maps.util.NavigationProgress+import com.vayunmathur.maps.util.NavigationService+import com.vayunmathur.maps.util.NavigationSessionManager+import com.vayunmathur.maps.util.NavigationSessionManager.NavState+import com.vayunmathur.maps.util.RouteService+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import org.maplibre.spatialk.geojson.Position+import java.util.TimeZone+import kotlin.math.roundToInt++/**+ * The main Android Auto screen (P12): a full-screen map drawn to the car+ * [android.view.Surface] by [CarMapRenderer], with a [NavigationTemplate] on top.+ *+ * While a navigation session is active (driven by the existing+ * [NavigationSessionManager] — the same singleton the phone uses) the template+ * shows the upcoming maneuver, step cue, distance to the maneuver, lane guidance+ * (P5a) and an ETA/remaining-distance [TravelEstimate], and the camera follows+ * the puck heading-up. When idle it shows the map centred on the current+ * location with a Search action.+ *+ * This screen only *renders* nav state and forwards camera/route/puck to the+ * renderer; all routing, progress, reroute and voice guidance stay in the+ * existing stack.+ */+class NavMapScreen(carContext: CarContext) : Screen(carContext) {++ private val renderer = CarMapRenderer(carContext)+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)++ init {+ lifecycle.addObserver(object : DefaultLifecycleObserver {+ override fun onCreate(owner: LifecycleOwner) {+ carContext.getCarService(AppManager::class.java)+ .setSurfaceCallback(renderer)+ // Prime the idle camera before the first nav fix arrives.+ pushCameraAndOverlay(NavigationSessionManager.state.value)+ }++ override fun onDestroy(owner: LifecycleOwner) {+ renderer.destroy()+ scope.cancel()+ }+ })++ scope.launch {+ NavigationSessionManager.state.collect { state ->+ pushCameraAndOverlay(state)+ invalidate()+ }+ }+ }++ override fun onGetTemplate(): Template {+ val state = NavigationSessionManager.state.value+ val builder = NavigationTemplate.Builder()+ .setActionStrip(buildActionStrip(state))++ when (state) {+ is NavState.Navigating -> {+ buildRoutingInfo(state.progress)?.let { builder.setNavigationInfo(it) }+ buildTravelEstimate(state.progress)?.let { builder.setDestinationTravelEstimate(it) }+ }+ NavState.Starting,+ NavState.Recalculating ->+ builder.setNavigationInfo(RoutingInfo.Builder().setLoading(true).build())+ else -> { /* idle / arrived / failed: map + action strip only */ }+ }+ return builder.build()+ }++ // ----------------------------------------------------------------+ // Renderer feeding+ // ----------------------------------------------------------------++ private fun pushCameraAndOverlay(state: NavState) {+ renderer.setRoute(NavigationSessionManager.currentRoute?.polyline ?: emptyList())+ val progress = (state as? NavState.Navigating)?.progress+ if (progress != null) {+ renderer.setPuck(progress.snappedPosition)+ renderer.setCamera(+ target = progress.snappedPosition,+ zoom = 17.0,+ bearing = progress.courseOverGround.toDouble(),+ tilt = 45.0,+ )+ } else {+ val pos = lastKnownPosition()+ if (pos != null) {+ renderer.setPuck(pos)+ renderer.setCamera(pos, 15.0, 0.0, 0.0)+ }+ }+ }++ // ----------------------------------------------------------------+ // Template building+ // ----------------------------------------------------------------++ private fun buildActionStrip(state: NavState): ActionStrip {+ val builder = ActionStrip.Builder()+ builder.addAction(+ Action.Builder()+ .setTitle(carContext.getString(R.string.car_search_action))+ .setOnClickListener { screenManager.push(CarSearchScreen(carContext)) }+ .build()+ )+ val navigating = state is NavState.Navigating ||+ state is NavState.Recalculating || state is NavState.Starting+ if (navigating) {+ builder.addAction(+ Action.Builder()+ .setTitle(carContext.getString(R.string.nav_action_end))+ .setOnClickListener { stopNavigation() }+ .build()+ )+ }+ return builder.build()+ }++ private fun buildRoutingInfo(progress: NavigationProgress): RoutingInfo? {+ val steps = NavigationSessionManager.currentRoute?.step ?: return null+ val info = RoutingInfo.Builder()+ // The maneuver the driver is approaching is the START of the next step;+ // distanceToNextManeuver counts down to it (matches NavigationTts).+ val upcomingIdx = progress.currentStepIndex + 1+ if (upcomingIdx in steps.indices) {+ info.setCurrentStep(+ carStep(steps[upcomingIdx], withLanes = true),+ metersToDistance(progress.distanceToNextManeuver),+ )+ val nextIdx = upcomingIdx + 1+ if (nextIdx in steps.indices) {+ info.setNextStep(carStep(steps[nextIdx], withLanes = false))+ }+ } else {+ // On the final step: point at the destination.+ val destName = NavigationSessionManager.destinationName+ ?: carContext.getString(R.string.nav_default_destination)+ val dest = Step.Builder(destName)+ .setManeuver(Maneuver.Builder(Maneuver.TYPE_DESTINATION).build())+ .build()+ info.setCurrentStep(dest, metersToDistance(progress.distanceRemaining))+ }+ return info.build()+ }++ private fun carStep(step: RouteService.Step, withLanes: Boolean): Step {+ val cue = step.navInstruction.instructions+ .ifBlank { carContext.getString(R.string.car_continue) }+ val builder = Step.Builder(cue)+ .setManeuver(CarManeuvers.build(step.navInstruction.maneuver))+ if (withLanes && step.lanes.isNotEmpty()) {+ CarManeuvers.lanes(step.lanes).forEach { builder.addLane(it) }+ }+ return builder.build()+ }++ private fun buildTravelEstimate(progress: NavigationProgress): TravelEstimate? {+ val arrival = DateTimeWithZone.create(progress.etaEpochMs, TimeZone.getDefault())+ val remainingSec = ((progress.etaEpochMs - System.currentTimeMillis()) / 1000)+ .coerceAtLeast(0)+ return TravelEstimate.Builder(metersToDistance(progress.distanceRemaining), arrival)+ .setRemainingTimeSeconds(remainingSec)+ .build()+ }++ private fun metersToDistance(meters: Double): Distance =+ if (meters < 1000.0) {+ Distance.create(meters.roundToInt().toDouble(), Distance.UNIT_METERS)+ } else {+ Distance.create(meters / 1000.0, Distance.UNIT_KILOMETERS_P1)+ }++ // ----------------------------------------------------------------+ // Helpers+ // ----------------------------------------------------------------++ private fun stopNavigation() {+ runCatching {+ carContext.startService(+ Intent(carContext, NavigationService::class.java)+ .apply { action = NavigationService.ACTION_STOP }+ )+ }+ }++ private fun lastKnownPosition(): Position? {+ if (ContextCompat.checkSelfPermission(+ carContext, Manifest.permission.ACCESS_FINE_LOCATION+ ) != PackageManager.PERMISSION_GRANTED+ ) return null+ val lm = carContext.getSystemService(Context.LOCATION_SERVICE) as? LocationManager+ ?: return null+ val loc: Location? = runCatching {+ lm.getLastKnownLocation(LocationManager.GPS_PROVIDER)+ ?: lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)+ }.getOrNull()+ return loc?.let { Position(longitude = it.longitude, latitude = it.latitude) }+ }+}
maps/src/main/res/values/strings.xml
diff --git a/maps/src/main/res/values/strings.xml b/maps/src/main/res/values/strings.xmlindex 953fae045f..4955029704 100644--- a/maps/src/main/res/values/strings.xml+++ b/maps/src/main/res/values/strings.xml@@ -387,4 +387,14 @@ <string name="parking_note_hint">Add a note (level, section…)</string> <!-- Parking sheet: clears the saved parking spot. Verb. --> <string name="parking_clear">Clear</string>++ <!-- Android Auto (P12) car app strings. -->+ <string name="car_search_title">Search</string>+ <string name="car_search_action">Search</string>+ <string name="car_recenter">Recenter</string>+ <string name="car_voice_hint">Tap search, then speak a place or address.</string>+ <string name="car_no_results">No results. Tap search to try again.</string>+ <string name="car_searching">Searching\u2026</string>+ <string name="car_route_failed">Couldn\'t find a route there.</string>+ <string name="car_continue">Continue</string> </resources>
maps/src/main/res/xml/automotive_app_desc.xml
diff --git a/maps/src/main/res/xml/automotive_app_desc.xml b/maps/src/main/res/xml/automotive_app_desc.xmlnew file mode 100644index 0000000000..021eb9815e--- /dev/null+++ b/maps/src/main/res/xml/automotive_app_desc.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Android Auto app descriptor (P12). Declares this app to the Android Auto+ host as a Car App Library "template" app so the projected host will surface+ our CarAppService. Referenced from AndroidManifest via the+ com.google.android.gms.car.application meta-data. -->+<automotiveApp>+ <uses name="template" />+</automotiveApp>