Modern Apps git

← Modern-Apps.git

various fixes

Commit
df361e43a05b8fd8da4eb43d28039b1011004719
Author
vayun-mathur <[email protected]>
When
2026-09-19 00:33 UTC (2 months ago)
Parents
001b85e

Diff

SPEC.md
diff --git a/SPEC.md b/SPEC.mdnew file mode 100644index 0000000000..a128b0a286--- /dev/null+++ b/SPEC.md@@ -0,0 +1,1316 @@+# Android Auto / Android Automotive — App-to-Car Interface Spec++> **Library:** `androidx.car.app:app-*` **`1.9.0-alpha02`** (9 Sept 2026)+> **Car App API Level:** **9** (`androidx.car.app.versioning.CarAppApiLevels.LEVEL_9`)+> **Release page:** `https://developer.android.com/jetpack/androidx/releases/car-app#1.9.0-alpha02`+> **Sources used:** `androidx/car/app/{app,app-automotive,app-projected,app-testing}/1.9.0-alpha02/*-sources.jar`+> from `https://dl.google.com/dl/android/maven2/androidx/car/app/`+> (325 `.java` files; this file is generated purely from those sources, not from any repo checkout)+>+> **Artifacts:**+>+> | Artifact | Gradle coordinate | Contains |+> |---|---|---|+> | `app` | `androidx.car.app:app:1.9.0-alpha02` | ALL core framework: service, session, screen, context, templates, models, managers |+> | `app-projected` | `androidx.car.app:app-projected:1.9.0-alpha02` | Android Auto / CarPlay projection: `ProjectedCarHardwareManager`, `ProjectedCarAudioRecord` |+> | `app-automotive` | `androidx.car.app:app-automotive:1.9.0-alpha02` | Android Automotive OS: `CarAppActivity` stack, `AutomotiveCarHardwareManager`, `AutomotiveCarAudioRecord` |+> | `app-testing` | `androidx.car.app:app-testing:1.9.0-alpha02` | `TestCarContext`, `TestScreenManager`, `FakeHost`, etc. |+>+> Dependencies:+>+> ```groovy+> implementation "androidx.car.app:app:1.9.0-alpha02"             // always+> implementation "androidx.car.app:app-projected:1.9.0-alpha02"  // Android Auto specific+> implementation "androidx.car.app:app-automotive:1.9.0-alpha02" // Automotive OS specific+> testImplementation "androidx.car.app:app-testing:1.9.0-alpha02"+> ```++---++## Table of contents++- [0. How an app talks to the car (mental model)](#0-how-an-app-talks-to-the-car-mental-model)+- [1. Manifest, service entry, host trust, versioning](#1-manifest-service-entry-host-trust-versioning)+- [2. Core runtime: Session / Screen / CarContext / managers](#2-core-runtime-session--screen--carcontext--managers)+- [3. Shared UI vocabulary (all app types)](#3-shared-ui-vocabulary-all-app-types)+- [4. Template × app-type matrix](#4-template--app-type-matrix)+- [5. Navigation apps](#5-navigation-apps-navigation)+- [6. POI / Parking / Charging apps](#6-poi--parking--charging-apps-poi)+- [7. Media apps](#7-media-apps-media-experimental-stable-hybrid)+- [8. Messaging apps](#8-messaging-apps-messaging)+- [9. Calling / Dialer apps](#9-calling--dialer-apps-calling)+- [10. Weather apps](#10-weather-apps-weather)+- [11. IoT apps](#11-iot-apps-iot)+- [12. Settings / sign-in / search / suggestions / notifications](#12-settings--sign-in--search--suggestions--notifications)+- [13. Vehicle hardware (all app types, API-gated)](#13-vehicle-hardware-all-app-types-api-gated)+- [14. Automotive-only vs Projected-only](#14-automotive-only-vs-projected-only)+- [15. Testing surface](#15-testing-surface)+- [16. Permissions, constraints, quotas](#16-permissions-constraints-quotas)+- [Appendix A: 1.9.0-alpha02 + alpha01 changelog](#appendix-a-190-alpha02--alpha01-changelog)+- [Appendix B: Full class index](#appendix-b-full-class-index)++---++## 0. How an app talks to the car (mental model)++```+Phone / head-unit app process              Car host process (Auto / AAOS / CP)+─────────────────────────────              ────────────────────────────────────+CarAppService (manifest-declared)+  └─ Session (per display: MAIN + CLUSTER)+       └─ Screen stack (ScreenManager push/pop)+            └─ Screen.onGetTemplate() ──Binder IPC──▶ host renders template+CarContext.getCarService(XxxManager) ◀──Binder IPC── host events (nav stop,+  AppManager / NavigationManager /            pan, alert cancel, search text,+  ConstraintManager / CarHardwareManager /    voice reply, keypad, etc.)+  SuggestionManager / MediaPlaybackManager+SurfaceCallback ──Surface──▶ app draws map itself (nav/POI only)+Notifications (CarAppExtender) ──▶ host HUN / rail / TBT+MediaSession token ──▶ host media UI (out-of-band via MediaCompat/Media3)+CarHardwareManager ──▶ vehicle properties (AAOS: VehiclePropertyIds; projected: host dispatch)+```++Rules that apply to **every** app type:++1. You never draw car UI directly (except a map `Surface`). You return **templates**+   (`androidx.car.app.model.*`, `navigation.model.*`, `media.model.*`, `dialer.*`,+   `model.signin.*`) from `Screen.onGetTemplate()` and the host renders them.+2. You never call the host directly. You call **managers** obtained from+   `CarContext.getCarService(...)` and receive host callbacks through delegates.+3. Everything is **API-level gated**. `CarContext.getCarAppApiLevel()` returns the+   negotiated level (1–9). Guard every `@RequiresCarApi(n)` call.+4. Every template/model validates client-side (`validateOrThrow`) — illegal combos throw+   before IPC. Host limits (list counts) come from `ConstraintManager.getContentLimit()`.+5. The task stack quota: max **5 templates per task**, last must be+   `NavigationTemplate | PaneTemplate | MessageTemplate`. Refreshes+   (same type + same main content) don't count; pops restore quota;+   `NavigationTemplate` resets quota.++---++## 1. Manifest, service entry, host trust, versioning++### 1.1 `androidx.car.app.CarAppService` (abstract, `app`)++The single entry point. The host binds to it.++```xml+<service android:name=".YourAppService" android:exported="true">+  <intent-filter>+    <action android:name="androidx.car.app.CarAppService" />+    <!-- exactly one (or more) of the categories below -->+    <category android:name="androidx.car.app.category.NAVIGATION" />+  </intent-filter>+</service>+<!-- required: declares oldest API your app understands -->+<meta-data android:name="androidx.car.app.minCarApiLevel" android:value="1" />+<!-- optional: theme for permission UI + brand opt-in (API 9) -->+<meta-data android:name="androidx.car.app.theme" android:resource="@style/CarAppTheme" />+```++Constants on `CarAppService`:++| Constant | Value | Since |+|---|---|---|+| `SERVICE_INTERFACE` | `androidx.car.app.CarAppService` | 1 |+| `CATEGORY_NAVIGATION_APP` | `androidx.car.app.category.NAVIGATION` | 1 |+| `CATEGORY_POI_APP` | `androidx.car.app.category.POI` | 1 (replaces parking/charging) |+| `CATEGORY_PARKING_APP` | `androidx.car.app.category.PARKING` | **@Deprecated** → use `POI` |+| `CATEGORY_CHARGING_APP` | `androidx.car.app.category.CHARGING` | **@Deprecated** → use `POI` |+| `CATEGORY_IOT_APP` | `androidx.car.app.category.IOT` | API 6 |+| `CATEGORY_SETTINGS_APP` | `androidx.car.app.category.SETTINGS` | API 6 |+| `CATEGORY_FEATURE_CLUSTER` | `androidx.car.app.category.FEATURE_CLUSTER` | API 6 |+| `CATEGORY_MESSAGING_APP` | `androidx.car.app.category.MESSAGING` | `@ExperimentalCarApi` |+| `CATEGORY_CALLING_APP` | `androidx.car.app.category.CALLING` | `@ExperimentalCarApi` |+| `CATEGORY_WEATHER_APP` | `androidx.car.app.category.WEATHER` | API 7 |+| `CATEGORY_MEDIA_APP` | `androidx.car.app.category.MEDIA` | API 8 |++Methods to override / final:++```java+public abstract HostValidator createHostValidator();+public Session onCreateSession();                                        // legacy+public Session onCreateSession(SessionInfo sessionInfo);                // API 6, per-display+@RequiresCarApi(9) @ExperimentalCarApi+public @ThemeSource int getCarAppThemeSource(); // default THEME_SOURCE_SYSTEM+// @IntDef: THEME_SOURCE_SYSTEM = 0, THEME_SOURCE_APP = 1+public final IBinder onBind(Intent intent);      // do NOT override+public final boolean onUnbind(Intent intent);    // returns true (asks onRebind)+public void onDestroy();                         // @CallSuper+public final HostInfo getHostInfo();+public final Session getSession(SessionInfo sessionInfo);+@Deprecated public final Session getCurrentSession();+```++ host `dump(AUTO_DRIVE)` → `CarAppBinder.onAutoDriveEnabled()` (AutoDrive test harness).++### 1.2 `androidx.car.app.validation.HostValidator` (`app`)++```java+TEMPLATE_RENDERER_PERMISSION = "android.car.permission.TEMPLATE_RENDERER";+ALLOW_ALL_HOSTS_VALIDATOR; // debug only!+boolean isValidHost(HostInfo host);+Map<String,List<String>> getAllowedHosts();+new HostValidator.Builder(context)+    .addAllowedHost("com.google.android.projection.gearhead", "<sha256>")+    .addAllowedHosts(R.array.hosts_allowlist_sample) // "digest,package" lines+    .build();+```++Semantics: same-UID → allow; allowlisted (package + SHA-256 DER lowercase hex) → allow;+`SYSTEM_UID` → allow; holds `TEMPLATE_RENDERER` (automotive API 31+) → allow.++### 1.3 `androidx.car.app.AppInfo`, `SessionInfo`, `HostInfo`, `HandshakeInfo`++```java+// AppInfo (@CarProtocol @KeepFields)+MIN_API_LEVEL_METADATA_KEY = "androidx.car.app.minCarApiLevel";+static AppInfo create(Context ctx); // throws if minCarApiLevel missing+int getMinCarAppApiLevel(); int getLatestCarAppApiLevel(); String getLibraryDisplayVersion();++// SessionInfo (@RequiresCarApi(6))+DISPLAY_TYPE_MAIN = 0; DISPLAY_TYPE_CLUSTER = 1; // cluster: NavigationTemplate only+SessionInfo(@DisplayType int displayType, String sessionId);+String getSessionId(); int getDisplayType();+List<Class<? extends Template>> getSupportedTemplates(@CarAppApiLevel int apiLevel);+DEFAULT_SESSION_INFO;++// HostInfo — HostInfo(String pkg, int uid); getPackageName(); getUid()+// HandshakeInfo — getHostCarAppApiLevel()+// SessionInfoIntentEncoder — containsSessionInfo(Intent); decode(Intent)+```++### 1.4 `androidx.car.app.versioning.CarAppApiLevels` / `CarAppApiLevel`++`CarAppApiLevel` is an `@IntDef{UNKNOWN, LEVEL_1..LEVEL_9}`.+`CarAppApiLevels`: `LEVEL_1=1 … LEVEL_9=9`, `UNKNOWN=0`,+`static int getLatest()`, `getOldest()=1`, `isValid(int)`.++| Level | What it unlocked |+|---|---|+| 1 | core services + parking/charging/nav templates |+| 2 | `SignInTemplate`, `LongMessageTemplate`, multi-variant `CarText`, `ConstraintManager`, `setCarAppResult`, map `ActionStrip`, pan/zoom |+| 3 | `CarHardwareManager` (`HARDWARE_SERVICE`) |+| 4 | AAOS, QR sign-in, `PlaceListMapTemplate.setCurrentLocationEnabled`, contrast check |+| 5 | voice/mic, `Alert`/`showAlert`, map-pane detail, responsive turn cards, map tap, nav-list non-places, POI zoom/pan, `OnContentRefreshListener` |+| 6 | cluster `SessionInfo`, `TabTemplate`, list FAB `addAction`, `Row.addAction/numericDecoration`, app-driven refresh flag |+| 7 | `Header`, `MapWithContentTemplate` (replaces `MapTemplate`/`PlaceListNavigationTemplate`/`RoutePreviewNavigationTemplate`), `GridTemplate.addAction/itemSize`, `COMPOSE_MESSAGE` |+| 8 | `SectionedItemTemplate` (+ Row/Grid/Chip/Condensed/Spotlight/Banner sections), `MediaPlaybackTemplate`, `MediaPlaybackManager.registerMediaPlaybackToken`, `TYPE_MEDIA_PLAYBACK`, `GridItem.Badge`, `Row.endImage`, indexable rows |+| **9** (this release, mostly `@ExperimentalCarApi`) | `THEME_SOURCE_SYSTEM/APP` + `getCarAppThemeSource()`; `Header.subtitle/background/startHeaderImage`; `SearchHeader` on `SectionedItemTemplate`; `TabStyle` + `TabTemplate.setStyle/setEndAction`; `Banner/BannerStyle/BannerElement/BannerSection`; `Background/Shape`; `CarIconStyle.setShape`; `MediaPlaybackStyle` + `MediaPlaybackTemplate.setBanner/setStyle`; `PaneTemplate.setBanner`; `CarProgressBar` on `Row/GridItem`; `NavigationManager.canSetVoiceAssistantCapabilities/setVoiceAssistantCapabilities` |++Annotations: `annotations.RequiresCarApi`, `annotations.ExperimentalCarApi`,+`annotations.CarProtocol`, `annotations.KeepFields`.++### 1.5 `androidx.car.app.features.CarFeatures` + `connection.CarConnection`++```java+// CarFeatures — PackageManager.hasSystemFeature wrapper+FEATURE_BACKGROUND_AUDIO_WHILE_DRIVING = "com.android.car.background_audio_while_driving";+FEATURE_CAR_APP_LIBRARY_MEDIA = "android.software.car.templates_host.media";+static boolean isFeatureEnabled(Context ctx, String feature);+// NOTE: no FEATURE_PARKING/CHARGING/IOT/WEATHER exists — gating is via categories.++// CarConnection — Auto vs AAOS detection+CAR_CONNECTION_STATE = "CarConnectionState";+ACTION_CAR_CONNECTION_UPDATED = "androidx.car.app.connection.action.CAR_CONNECTION_UPDATED";+CONNECTION_TYPE_NOT_CONNECTED = 0; CONNECTION_TYPE_NATIVE = 1; // AAOS+CONNECTION_TYPE_PROJECTION = 2;                                // AA / CP+new CarConnection(ctx).getType() : LiveData<Integer>+```++---++## 2. Core runtime: Session / Screen / CarContext / managers++### 2.1 `androidx.car.app.Session implements LifecycleOwner` (`app`)++```java+public Session();+public abstract Screen onCreateScreen(Intent intent); // first screen; may pre-push+public void onNewIntent(Intent intent);               // default no-op+public void onCarConfigurationChanged(Configuration cfg);+public Lifecycle getLifecycle(); // ON_CREATE→onCreateScreen; START=visible; RESUME=interactive+public final CarContext getCarContext(); // valid iff State >= CREATED+```++### 2.2 `androidx.car.app.Screen implements LifecycleOwner` (`app`)++```java+protected Screen(CarContext carContext);+public abstract Template onGetTemplate();+public final void invalidate(); // → AppManager.invalidate(); no-op if State < STARTED+public final void finish();     // → ScreenManager.remove(this); no-op if root+public void setResult(Object result);+public String getMarker(); public void setMarker(String marker); // popTo(marker)+public final CarContext getCarContext();+public final ScreenManager getScreenManager();+public final Lifecycle getLifecycle();+```++`onGetTemplate()` quota (enforced host-side, documented on `Screen`):+max 5 templates/task; last must be `NavigationTemplate|PaneTemplate|MessageTemplate`;+refresh = same type + same main content (not counted); pop restores quota;+`NavigationTemplate` resets quota; notification/launcher intent resets quota;+host throttles rapid `invalidate()`.++### 2.3 `androidx.car.app.ScreenManager implements Manager` (`app`)++`CarContext.SCREEN_SERVICE = "screen"`.++```java+Screen getTop(); int getStackSize(); Collection<Screen> getScreenStack();+void push(Screen screen); // move-to-top if present; single-use (DESTROYED throws)+void pushForResult(Screen screen, OnScreenResultListener listener);+void pop();               // no-op if size<=1; new top reuses last template id+void popTo(String marker);+void popToRoot();+void remove(Screen screen); // direct remove → immediate ON_DESTROY+```++### 2.4 `androidx.car.app.CarContext extends ContextWrapper` (`app`)++```java+// service names+APP_SERVICE = "app";                 // AppManager+NAVIGATION_SERVICE = "navigation";   // NavigationManager+SCREEN_SERVICE = "screen";           // ScreenManager+CONSTRAINT_SERVICE = "constraints";  // ConstraintManager (API 2)+CAR_SERVICE = "car";                 // internal+HARDWARE_SERVICE = "hardware";       // CarHardwareManager (API 3)+SUGGESTION_SERVICE = "suggestion";   // SuggestionManager (API 5)+MEDIA_PLAYBACK_SERVICE = "media_playback"; // MediaPlaybackManager (API 8)++Object getCarService(String name);+<T> T getCarService(Class<T> clz);+String getCarServiceName(Class<?> clz);++void startCarApp(Intent intent); // ACTION_NAVIGATE geo:…, ACTION_DIAL/ACTION_CALL tel:…, own CarAppService+void finishCarApp();+static void startCarApp(Intent notifIntent, Intent appIntent); // @Deprecated → CarPendingIntent+@RequiresCarApi(2) void setCarAppResult(int resultCode, Intent data); // AAOS only (Auto: no-op)+@RequiresCarApi(2) ComponentName getCallingComponent();               // AAOS only (Auto: null)+boolean isDarkMode(); // nav apps MUST redraw map; change via Session.onCarConfigurationChanged+OnBackPressedDispatcher getOnBackPressedDispatcher(); // default: pop+int getCarAppApiLevel(); // throws if handshake incomplete+HostInfo getHostInfo();+void requestPermissions(List<String> perms, OnRequestPermissionsListener l);+void requestPermissions(List<String> perms, Executor ex, OnRequestPermissionsListener l);+// branding: androidx.car.app.theme → carPermissionActivityLayout+EXTRA_START_CAR_APP_BINDER_KEY;+ACTION_NAVIGATE = "androidx.car.app.action.NAVIGATE"; // geo:lat,lng · geo:0,0?q=addr+```++### 2.5 `androidx.car.app.AppManager` (`APP_SERVICE`, `app`)++```java+void setSurfaceCallback(SurfaceCallback cb); // needs ACCESS_SURFACE; main thread; null to clear+void invalidate();                            // re-query onGetTemplate()+void showToast(CharSequence text, @CarToast.Duration int duration);+@RequiresCarApi(5) void showAlert(Alert alert);   // nav templates only+@RequiresCarApi(5) void dismissAlert(int alertId);+// @RestrictTo(LIBRARY) openMicrophone(OpenMicrophoneRequest) — voice entry+```++`androidx.car.app.SurfaceCallback`:++```java+void onSurfaceAvailable(SurfaceContainer sc); // MUST Surface#release() when done+void onVisibleAreaChanged(Rect r); void onStableAreaChanged(Rect r);+void onSurfaceDestroyed(SurfaceContainer sc);+@RequiresCarApi(2) void onScroll(float dx, float dy);+@RequiresCarApi(2) void onFling(float vx, float vy);+@RequiresCarApi(2) void onScale(float fx, float fy, float scale);+@RequiresCarApi(5) void onClick(float x, float y); // touch not universal — always offer zoom strip+```++`androidx.car.app.SurfaceContainer`: `getSurface()`, `getWidth/Height/Dpi()`.++`androidx.car.app.CarToast`: `LENGTH_SHORT/LONG`,+`makeText(CarContext, CharSequence|@StringRes, int).setText().setDuration().show()`.++---++## 3. Shared UI vocabulary (all app types)++### 3.1 `androidx.car.app.model.Action` (`@CarProtocol`, `app`)++Types: `TYPE_CUSTOM=1`, `TYPE_APP_ICON`, `TYPE_BACK`, `TYPE_PAN`,+`TYPE_COMPOSE_MESSAGE` (API 7), `TYPE_MEDIA_PLAYBACK` (API 8; **API 9: row-only, FAB ignored**),+`TYPE_IN_CALL_HEADER` (dialer). Flags: `FLAG_PRIMARY` (API 4),+`FLAG_IS_PERSISTENT` / `FLAG_DEFAULT` (API 5).+Singletons: `APP_ICON / BACK / PAN / COMPOSE_MESSAGE / MEDIA_PLAYBACK`.++```java+CarText getTitle(); CarIcon getIcon(); CarColor getBackgroundColor();+int getType(); int getFlags(); boolean isStandard();+@RequiresCarApi(5) boolean isEnabled();+OnClickDelegate getOnClickDelegate();+new Action.Builder()+  .setTitle(CharSequence|CarText).setIcon(CarIcon)+  .setOnClickListener(OnClickListener) // or ParkedOnlyOnClickListener+  .setBackgroundColor(CarColor).setEnabled(boolean).setFlags(int).build();+```++`ActionStrip`: `getActions()`, `getFirstActionOfType(int)`;+`Builder.addAction(Action)` rejects duplicate non-custom types.++### 3.2 `androidx.car.app.model.Header` (API 5) + `SearchHeader` (API 9)++```java+// Header (@RequiresCarApi(5))+CarText getTitle(); Action getStartHeaderAction(); // APP_ICON|BACK only+List<Action> getEndHeaderActions();+@RequiresCarApi(9) CarText getSubtitle(); Background getBackground(); CarIcon getStartHeaderImage();+new Header.Builder()+  .setTitle(CharSequence|CarText).setStartHeaderAction(Action)+  .addEndHeaderAction(Action) // icon-only inside map content+  .setSubtitle(...)                                    // API 9 experimental+  .setBackground(Background)                           // API 9 experimental+  .setStartHeaderImage(CarIcon custom)                 // API 9 experimental+  .build(); // requires title OR start action++// SearchHeader (@RequiresCarApi(9) @ExperimentalCarApi) — SectionedItemTemplate only+new SearchHeader.Builder(SearchCallback cb)+  .setInitialSearchText(String).setSearchHint(String)+  .setShowKeyboardByDefault(boolean) // default true+  .setStartHeaderAction(Action).setEndHeaderActions(List<Action>).build();+```++`SearchCallback` (shared): `default onSearchTextChanged(String)` (coalesced),+`default onSearchSubmitted(String)`.++### 3.3 Rows / lists / grids / text / icons++```java+// Row implements Item+IMAGE_TYPE_SMALL / IMAGE_TYPE_LARGE; IMAGE_TYPE_EXTRA_SMALL / IMAGE_TYPE_MEDIUM (API 8);+@Deprecated IMAGE_TYPE_ICON → use SMALL/MEDIUM (untinted by default);+NO_DECORATION = -1;+getTitle()/getTexts()/getImage()/getRowImageType();+getEndImage()/getRowEndImageType(); // API 8+getActions(); // API 6, max 2   getNumericDecoration(); // API 6+getToggle(); getOnClickDelegate(); getMetadata(); isBrowsable(); isEnabled(); // API 5+isIndexable(); // API 8+getProgressBar(); // API 9 CarProgressBar+new Row.Builder()+  .setTitle(...).addText(...).setImage(CarIcon[,type]).setEndImage(...)+  .setBrowsable(...).setToggle(Toggle).setOnClickListener(...)+  .setMetadata(Metadata|Place).setEnabled(...).setIndexable(...)+  .setProgressBar(CarProgressBar).addAction(Action).setNumericDecoration(int).build();++// GridItem implements Item+getTitle()/getText()/getImage()/getBadge(); // Badge API 8+isIndexable(); // API 8   getProgressBar(); // API 9 (mutually exclusive with text)+isLoading(); getOnClickDelegate();+new GridItem.Builder().setTitle(...).setText(...).setImage(CarIcon[,Badge])+  .setOnClickListener(...).setIndexable(...).setProgressBar(...).setLoading(...).build();++// Pane — getRows()/getActions()/getImage() (API 4)/isLoading()+// ItemList — getItems()/getSelectedIndex()/getOnSelectedDelegate()/+//   getOnItemVisibilityChangedDelegate()/getNoItemsMessage()+//   OnSelectedListener.onSelected(int); OnItemVisibilityChangedListener.onItemVisibilityChanged(int,int)+// Item (marker); SectionedItemList.create(ItemList, CharSequence header);+// Section<?> + RowSection/GridSection/ChipSection/CondensedSection/SpotlightSection/BannerSection+// CondensedItem (dense 1-line), Chip (+ChipStyle), Toggle, Metadata,+// Place/PlaceMarker/CarLocation, Alert/AlertCallback,+// CarText/CarSpan/DistanceSpan/DurationSpan/ForegroundCarColorSpan/CarIconSpan/ClickableSpan/TimerSpan,+// Distance.create(double,@Unit int) [UNIT_METERS/KILOMETERS/KILOMETERS_P1/MILES/MILES_P1/FEET/YARDS],+// DateTimeWithZone.create(long,int,String|TimeZone|ZonedDateTime),+// CarColor (STANDARD_ONLY vs UNCONSTRAINED), CarIcon (see below)++// CarIcon+Types: CUSTOM/BACK/ALERT/APP_ICON/ERROR/PAN(API2)/COMPOSE_MESSAGE(API7)/MEDIA_PLAYBACK(API8);+Singletons: APP_ICON/BACK/ALERT/ERROR/PAN/COMPOSE_MESSAGE/MEDIA_PLAYBACK;+createTintedIcon(IconCompat) / createOriginalIcon(IconCompat);+new CarIcon.Builder(IconCompat[,CarIconStyle]|CarIcon).setTint[deprecated].setStyle(CarIconStyle).build();++// CarIconStyle — TINTED (default tint) / ORIGINAL (no tint: avatars/art)+//   getTint(); getShape(); // API 9  new Builder(base).setTint(CarColor).setShape(Shape).build()+// Background (API 9 exp) — TRANSPARENT; getColor()/getImage() (exactly one);+//   Builder.setColor(CarColor)/setImage(CarIcon TYPE_CUSTOM).build() (COLOR_ONLY)+// Shape (API 9 exp) — NONE/CORNER_EXTRA_SMALL/SMALL/MEDIUM/LARGE/EXTRA_LARGE/FULL+// CarProgressBar (API 9 exp) — for Row/GridItem; + CarProgressBarStyle/StrokeCap+```++### 3.4 `androidx.car.app.model.Tab / TabContents / TabStyle` (API 6 / style API 9)++```java+// TabContents implements Content — CONTENT_ID="TAB_CONTENTS_CONTENT_ID"+new TabContents.Builder(Template t).build();+// API 6: List|Pane|Grid|Message|Search; API 7: +Navigation; API 8: +SectionedItem+// Tab implements Content — getTitle()/getIcon()/getContentId()/getStyle() (API 9)+//   Builder.setTitle/setIcon/setContentId/setStyle(TabStyle)+// TabStyle (API 9 exp) — getShape()/getSelectedBackgroundColor()/getTextColor()+//   Builder.setShape(Shape).setSelectedBackgroundColor(CarColor).setTextColor(CarColor).build() (≥1)+```++---++## 4. Template × app-type matrix++Base: `androidx.car.app.model.Template` (marker interface).++| Template | Min API | Used by app types |+|---|---|---|+| `model.PaneTemplate` (+`Pane`) | 1 (banner API 9) | NAV, POI, WEATHER, IOT, SETTINGS |+| `model.ListTemplate` (single `ItemList` or `SectionedItemList`s, ≤100 items) | 1 (FAB API 6, Header API 7) | NAV, POI, WEATHER, IOT, MEDIA (browse lists), MESSAGING (conversations) |+| `model.SectionedItemTemplate` (+ Row/Grid/Chip/Condensed/Spotlight/Banner sections) | 8 (`SearchHeader`/styles API 9) | POI, WEATHER, IOT, MEDIA, MESSAGING |+| `model.GridTemplate` (`GridItem`-only) | 1 (actions API 7, size/shape API 8) | POI, WEATHER, IOT, MEDIA |+| `model.MessageTemplate` | 1 | ALL (task end / empty / error) |+| `model.LongMessageTemplate` (parked-only) | 2 | SETTINGS, POI (terms, details) |+| `model.SearchTemplate` | 1 | NAV, POI, MEDIA, MESSAGING |+| `model.PlaceListMapTemplate` (host map + list) | 1 (refresh API 5) | NAV, POI |+| `navigation.model.NavigationTemplate` (active nav) | 1 | NAV only |+| `navigation.model.MapWithContentTemplate` (app map + overlay) | 7 (SectionedItem content API 8) | NAV (+ POI map via `MAP_TEMPLATES`) |+| `navigation.model.MapTemplate` | 5, **@Deprecated** → `MapWithContentTemplate` | NAV |+| `navigation.model.PlaceListNavigationTemplate` | 1, **@Deprecated** | NAV |+| `navigation.model.RoutePreviewNavigationTemplate` | 1, **@Deprecated** | NAV |+| `model.TabTemplate` (2–4 tabs) | 6 (style/endAction API 9) | POI, WEATHER, IOT, MEDIA, NAV |+| `media.model.MediaPlaybackTemplate` | 8 (banner/style API 9) | MEDIA |+| `model.signin.SignInTemplate` (parked-only) | 2 (QR API 4) | ALL (login) |+| `dialer.InCallTemplate` | `@ExperimentalCarApi` | CALLING |+| `dialer.TelephoneKeypadTemplate` | `@ExperimentalCarApi` | CALLING |++`model.TemplateInfo(Class<? extends Template>, String)` / `TemplateWrapper` are host-only.++---++## 5. Navigation apps (`NAVIGATION`)++Manifest: `androidx.car.app.category.NAVIGATION`.+Permissions: `androidx.car.app.NAVIGATION_TEMPLATES` (nav templates),+`androidx.car.app.MAP_TEMPLATES` (`PlaceListMapTemplate` / map side of `MapWithContentTemplate`;+self-drawn nav maps exempt), `androidx.car.app.ACCESS_SURFACE` (custom map surface).++### 5.1 `androidx.car.app.navigation.NavigationManager` (`NAVIGATION_SERVICE`)++```java+NavigationManager mgr = carContext.getCarService(NavigationManager.class);+mgr.setNavigationManagerCallback(cb);              // or (Executor, cb)+mgr.clearNavigationManagerCallback();              // throws if navigating+mgr.navigationStarted();  // idempotent; needs callback; claims single-active-nav+mgr.updateTrip(Trip trip); // only after started; dropped after ended/onStopNavigation+mgr.navigationEnded();    // idempotent+@RequiresCarApi(9) @ExperimentalCarApi+boolean canSetVoiceAssistantCapabilities(); // api>=9 && FEATURE_AUTOMOTIVE+void setVoiceAssistantCapabilities(NavigationVoiceAssistantCapabilities caps); // AAOS only++interface NavigationManagerCallback {+  default void onStopNavigation();   // stop routing + voice + notifications + updateTrip+  default void onAutoDriveEnabled(); // AutoDrive test: simulate until finishCarApp()+}+```++There is **no** `startNavigation/stopNavigation`, **no** `SurfaceRenderer`, **no** `CameraMode`,+**no** `TripPreview`, **no** `AlertManager` in 1.9.0-alpha02 — use the names above.++### 5.2 Trip graph (`navigation.model.*`)++```java+// Trip — getDestinations()/getSteps()/getDestinationTravelEstimates()/+//   getStepTravelEstimates()/getCurrentRoad()/isLoading()+new Trip.Builder()+  .addDestination(Destination, TravelEstimate).addStep(Step, TravelEstimate) // in order+  .setCurrentRoad(CharSequence) // spans ignored+  .setLoading(boolean)          // true + steps → IllegalArgumentException+  .build(); // size-match checks; floating bar = Step[0].cue + Estimate[0].distance + Maneuver.icon++// Step — getManeuver()/getLanes()/getLanesImage()/getCue()/getRoad()+new Step.Builder() | Builder(CharSequence|CarText cue)+  .setManeuver(Maneuver).addLane(Lane) // left→right; cluster/HUD primary+  .setLanesImage(CarIcon)              // 500×74dp bbox; needs lanes data+  .setCue(CharSequence)                // CarIconSpan|DistanceSpan|DurationSpan+  .setRoad(CharSequence)               // TEXT_ONLY+  .build();++// TravelEstimate — REMAINING_TIME_UNKNOWN = -1+getRemainingDistance()/getRemainingTimeSeconds()/getArrivalTimeAtDestination()/+// getRemainingTimeColor()/getRemainingDistanceColor() (STANDARD_ONLY)/+// getTripText()/getTripIcon() (API 5)+new TravelEstimate.Builder(Distance, DateTimeWithZone|ZonedDateTime)+  .setRemainingTimeSeconds(long).setRemainingTime(Duration) // API 26+  .setRemainingTimeColor(CarColor).setRemainingDistanceColor(CarColor)+  .setTripText(CarText).setTripIcon(CarIcon).build();++// Destination — getName()/getAddress()/getImage() (128×128dp)+new Destination.Builder().setName(...).setAddress(...).setImage(CarIcon).build();+//   (name or address non-empty required)++// RoutingInfo implements NavigationTemplate.NavigationInfo+getCurrentStep()/getCurrentDistance()/getNextStep()/getJunctionImage()/isLoading();+new RoutingInfo.Builder()+  .setCurrentStep(Step, Distance) // cue images 216×72dp+  .setNextStep(Step).setJunctionImage(CarIcon) // 500×312dp, aspect ≥ 1.6+  .setLoading(boolean).build();++// MessageInfo implements NavigationTemplate.NavigationInfo — off-route / guidance text+new MessageInfo.Builder(CharSequence|CarText title).setTitle(...).setText(...).setImage(...).build();+```++### 5.3 Voice assistant (API 9, AAOS only)++```java+// navigation.model.NavigationVoiceAssistantCapabilities (@ExperimentalCarApi @RequiresCarApi(9))+boolean isVoiceAssistantConsentGranted();+Set<Integer> getSupportedActions(); Set<Integer> getSupportedDisruptions();+new Builder()+  .setVoiceAssistantConsentGranted(boolean) // default false+  .addSupportedAction(@VoiceAssistantAction int)+  .addSupportedDisruption(@VoiceAssistantDisruption int).build();+// Actions: ACTION_UNDEFINED=0, ALLOW_AND_AVOID_FERRIES=1, ALLOW_AND_AVOID_HIGHWAYS=2,+//   ALLOW_AND_AVOID_TOLLS=3, CLEAR_SEARCH_RESULTS=4, EXIT_NAVIGATION=5, FOLLOW_MODE=6,+//   MUTE_AND_UNMUTE=7, ROUTE_OVERVIEW=8, SHOW_ALTERNATES=9, SHOW_DIRECTIONS_LIST=10,+//   SHOW_SATELLITE=11, SHOW_TRAFFIC=12+// Disruptions: DISRUPTION_REPORT_UNDEFINED=0, CONSTRUCTION=1, CRASH=2, FLOODING=3, FOG=4,+//   OBJECT_ON_ROAD=5, POLICE=6, POTHOLE=7, ROAD_CLOSURE=8, SNOW=9, TRAFFIC=10, VEHICLE=11+```++### 5.4 Map rendering++```java+// navigation.model.NavigationTemplate implements Template — active guidance+// requires NAVIGATION_TEMPLATES; any-content refresh (quota-exempt + quota-reset);+// NO own surface — draw via AppManager.setSurfaceCallback+interface NavigationInfo {} // impls: RoutingInfo, MessageInfo+getNavigationInfo()/getDestinationTravelEstimate()/getBackgroundColor()/+getActionStrip() // required, NAVIGATION max 4+getMapActionStrip()/getPanModeDelegate(); // API 2+new NavigationTemplate.Builder()+  .setNavigationInfo(NavigationInfo).setDestinationTravelEstimate(TravelEstimate)+  .setBackgroundColor(CarColor) // UNCONSTRAINED+  .setActionStrip(ActionStrip).setMapActionStrip(ActionStrip) // MAP max 4 icon-only+  .setPanModeListener(PanModeListener).build();++// navigation.model.MapController (@RequiresCarApi(5))+getMapActionStrip()/getPanModeDelegate();+new MapController.Builder().setMapActionStrip(ActionStrip).setPanModeListener(...).build();+// without Action.PAN: no SurfaceCallback pan gestures, host exits pan++// navigation.model.MapWithContentTemplate (@RequiresCarApi(7)) — REPLACES all below+// requires NAVIGATION_TEMPLATES *or* MAP_TEMPLATES+getContentTemplate()/getMapController()/getActionStrip();+new Builder().setContentTemplate(Template)+  // API 7: List|Pane|Grid|Message; API 8+: +SectionedItemTemplate+  .setMapController(MapController).setActionStrip(ActionStrip).build();++// @Deprecated (use MapWithContentTemplate):+//   navigation.model.MapTemplate (API 5) — getMapController/getPane/getItemList/getHeader/getActionStrip+//   navigation.model.PlaceListNavigationTemplate — rows: small images only, no image+marker,+//     non-browsable require DistanceSpan+//   navigation.model.RoutePreviewNavigationTemplate — needs OnSelectedListener,+//     every row DistanceSpan|DurationSpan; do NOT continuously refresh while moving+// Generic (non-NAV permission): model.PlaceListMapTemplate — see §6.++// navigation.model.Maneuver — getType()/getRoundaboutExitNumber()/getRoundaboutExitAngle()/getIcon()+new Maneuver.Builder(@Type int).setIcon(CarIcon 128×128dp)+  .setRoundaboutExitNumber(1..).setRoundaboutExitAngle(1..360).build();+// Types 0..50 incl. UNKNOWN/DEPART/NAME_CHANGE/KEEP_LEFT/RIGHT/TURN_*_LEFT/RIGHT/+//   U_TURN_*/ON_RAMP_*/OFF_RAMP_*/FORK_*/MERGE_*/ROUNDABOUT_*_CW/CCW/STRAIGHT/+//   FERRY_BOAT/TRAIN/DESTINATION* — full list in sources (Maneuver.java).++// navigation.model.Lane — getDirections(); Builder.addDirection(LaneDirection).build()+// navigation.model.LaneDirection — create(@Shape int, boolean recommended)+//   SHAPE_UNKNOWN=1, STRAIGHT=2, SLIGHT_LEFT=3, SLIGHT_RIGHT=4, NORMAL_LEFT=5,+//   NORMAL_RIGHT=6, SHARP_LEFT=7, SHARP_RIGHT=8, U_TURN_LEFT=9, U_TURN_RIGHT=10+// PanModeListener.onPanModeChanged(boolean);+// PanModeDelegate.sendPanModeChanged(boolean, OnDoneCallback) (API 2)++// Map anchors/markers:+// model.Place — new Place.Builder(CarLocation).setMarker(PlaceMarker).build()+// model.PlaceMarker — TYPE_ICON=0 (64×64dp, tintable) / TYPE_IMAGE=1 (72×72dp, no color)+//   setIcon(CarIcon,@MarkerIconType).setLabel(CharSequence ≤3).setColor(CarColor).build()+// model.CarLocation — create(lat,lng) / create(Location)+```++### 5.5 Alerts (nav only — no `AlertManager`; via `AppManager`)++```java+// AppManager.showAlert(Alert) / dismissAlert(int) (@RequiresCarApi(5))+// only navigation templates; unsupported template → REASON_NOT_SUPPORTED; same id replaces.+// model.Alert (@RequiresCarApi(5)) — DURATION_SHOW_INDEFINITELY = MAX_VALUE; MAX_ACTION_COUNT = 2+getId()/getTitle()/getSubtitle()/getIcon() (88×88dp)/getActions()/getDurationMillis()/getCallbackDelegate();+new Alert.Builder(int alertId, CarText title, long durationMillis)+  .setSubtitle(CarText).setIcon(CarIcon).addAction(Action max 2).setCallback(AlertCallback).build();+// model.AlertCallback — REASON_TIMEOUT=1/REASON_USER_ACTION=2/REASON_NOT_SUPPORTED=3+//   onCancel(@Reason int); onDismiss()+// Frequent driving alerts discouraged — prefer notification channel + CarAppExtender (see §12).+```++---++## 6. POI / Parking / Charging apps (`POI`)++Manifest: `androidx.car.app.category.POI`+(current name for deprecated `PARKING` / `CHARGING`).+Permissions: `MAP_TEMPLATES` (for `PlaceListMapTemplate`), `ACCESS_SURFACE` (custom map),+location (`ACCESS_FINE/COARSE_LOCATION`) for `setCurrentLocationEnabled`.++Primary templates: `SectionedItemTemplate` (API 8),+`TabTemplate` (API 6), `GridTemplate`, `ListTemplate`, `PaneTemplate`,+`PlaceListMapTemplate`, `MapWithContentTemplate` (map side via `MAP_TEMPLATES`),+`SearchTemplate`, `SignInTemplate`, `MessageTemplate`.++```java+// model.PlaceListMapTemplate — host-drawn map + ItemList+// refresh iff: prior loading, or title + row count/titles unchanged, or OnContentRefreshListener (API 5, quota-exempt)+isCurrentLocationEnabled()/getTitle()/getHeaderAction()/getActionStrip()/+isLoading()/getItemList()/getAnchor()/getOnContentRefreshDelegate(); // API 5+new PlaceListMapTemplate.Builder()+  .setCurrentLocationEnabled(boolean) // needs location perm; host may pull location+  .setLoading(boolean).setHeaderAction(APP_ICON|BACK).setTitle(CharSequence|CarText TEXT_ONLY)+  .setItemList(ItemList) // ROW_LIST_CONSTRAINTS_SIMPLE + non-browsable need DistanceSpan+                         // + small images only + no image+marker; limit CONTENT_LIMIT_TYPE_PLACE_LIST+  .setActionStrip(ActionStrip) // NAVIGATION max 4+  .setAnchor(Place)            // viewport reference (e.g. search centre)+  .setOnContentRefreshListener(OnContentRefreshListener) // API 5+  .build();++// model.SectionedItemTemplate (@RequiresCarApi(8)) — the POI workhorse+getSections()/getActions() (FAB)/getHeader()/getSearchHeader() (API 9)/+isLoading()/getAlphabeticalIndexingStrategy()/getScrollStatePersistenceStrategy();+new SectionedItemTemplate.Builder()+  .setSections(List)/addSection(Section)/clearSections()+    // only ChipSection (first, max 1) | RowSection | GridSection |+    //        CondensedSection | SpotlightSection | BannerSection+  .setActions/addAction (FAB: max 2 CUSTOM/COMPOSE_MESSAGE/MEDIA_PLAYBACK, icon+bg)+  .setHeader(Header) / .setSearchHeader(SearchHeader) // mutually exclusive+  .setLoading(boolean)+  .setAlphabeticalIndexingStrategy(DISABLED/TITLE_AS_IS/TITLE_IGNORE_ARTICLES_AND_SYMBOLS)+  .setScrollStatePersistenceStrategy(RESET_TO_TOP/PRESERVE_INDEX).build();++// Sections (model.*):+// GridSection (API 8): ITEM_SIZE_SMALL/MEDIUM/LARGE/EXTRA_LARGE,+//   ITEM_IMAGE_SHAPE_UNSET/CIRCLE, getIncompleteLastRowStrategy() (API 9)+// ChipSection (API 9 exp): ≥1 Chip; getStyle():ChipStyle+// CondensedSection (API 9 exp): CondensedItem dense rows; INCOMPLETE_LAST_ROW_AS_IS/TRUNCATE+// SpotlightSection (API 8/9): hero cards (hero image + condensed items)+// BannerSection (API 9 exp): exactly 1 Banner; Banner/BannerElement/BannerStyle+//   BannerStyle: getShape()/getBackground(); Builder.setShape(Shape).setBackground(Background)+// RowSection, Section<T>, SectionHeader, SectionedItemList+```++---++## 7. Media apps (`MEDIA`, experimental-stable hybrid)++Manifest: `androidx.car.app.category.MEDIA` (API 8).+Permissions: `androidx.car.app.MEDIA_TEMPLATES`.+Feature: `CarFeatures.FEATURE_CAR_APP_LIBRARY_MEDIA`.+**Browse is delegated** — `MediaBrowserServiceCompat` / Media3 `MediaLibraryService`.+The car-app lib only transports hints, extras, token, and the playback template.+`PlaybackStateCompat` is never referenced directly — the host reads the session out-of-band.++```java+// media.model.MediaPlaybackTemplate (@RequiresCarApi(8) @CarProtocol)+// PREREQUISITE: MediaPlaybackManager.registerMediaPlaybackToken()+// API 9+: host renders persistent entrypoint; app MUST handle+//   MediaConstants.ACTION_SHOW_MEDIA_PLAYBACK in Session.onNewIntent+getHeader()/getBanner() (API 9 exp)/getStyle() (API 9 exp);+new MediaPlaybackTemplate.Builder()+  .setHeader(Header).setBanner(Banner).setStyle(MediaPlaybackStyle).build();+// constraint: header/banner/style only; media apps max 1 FAB on API 9+ (host drops extras)++// media.model.MediaPlaybackStyle (@RequiresCarApi(9) @ExperimentalCarApi)+getMediaAccentColor()/getProgressBarStrokeCap();+new MediaPlaybackStyle.Builder()+  .setMediaAccentColor(CarColor|null) // UNCONSTRAINED+  .setProgressBarStrokeCap(@StrokeCap int) // default StrokeCap.DEFAULT+  .build(); // progress mirrors active MediaSession/MediaSessionCompat++// media.MediaPlaybackManager (@RequiresCarApi(8)) — CarContext.MEDIA_PLAYBACK_SERVICE+MediaPlaybackManager m = carContext.getCarService(MediaPlaybackManager.class);+m.registerMediaPlaybackToken(MediaSessionCompat.Token token); // @MainThread++// media.MediaConstants (Kotlin object)+ACTION_SHOW_MEDIA_PLAYBACK = "androidx.car.app.media.action.SHOW_MEDIA_PLAYBACK";++// Voice/mic shared with messaging + nav search:+// media.CarAudioRecord (@RequiresCarApi(5) abstract) — CarContext.create →+//   AutomotiveCarAudioRecord (automotive) | ProjectedCarAudioRecord (projected)+AUDIO_CONTENT_SAMPLING_RATE=16000; AUDIO_CONTENT_BUFFER_SIZE=512; AUDIO_CONTENT_MIME="audio/l16";+startRecording(); stopRecording(); read(byte[],off,size):int; // -1 = dismissed+// + CarAudioCallback.onStopRecording(), OpenMicrophoneRequest(CarAudioCallback),+//   OpenMicrophoneResponse(InputStream + PFD), delegates++// mediaextensions.* — hints/extras only, no UI:+// MediaBrowserExtras: KEY_ROOT_HINT_MEDIA_HOST_VERSION,+//   KEY_ROOT_HINT_MEDIA_SESSION_API (1/2/3), KEY_ROOT_HINT_MAX_QUEUE_ITEMS_WHILE_RESTRICTED,+//   KEY_HINT_VIEW_MAX_ITEMS_WHILE_RESTRICTED, ..._PER_ROW / ..._CATEGORY_... variants+// MediaIntentExtras: ACTION_MEDIA_TEMPLATE_V2, EXTRA_KEY_MEDIA_COMPONENT/_MEDIA_ID/+//   EXTRA_KEY_SEARCH_QUERY/_SEARCH_ACTION (0=NONE, 1=PLAY_FIRST_ITEM_FROM_SEARCH)+// MetadataExtras (MediaMetadataCompat / media3 MediaMetadata extras):+//   KEY_SUBTITLE_LINK_MEDIA_ID, KEY_DESCRIPTION_LINK_MEDIA_ID,+//   KEY_IMMERSIVE_AUDIO, KEY_EXCLUDE_MEDIA_ITEM_FROM_MIXED_APP_LIST,+//   KEY_CONTENT_FORMAT_TINTABLE_LARGE_ICON_URI/SMALL_ICON_URI,+//   KEY_TINTABLE_INDICATOR_ICON_URI_LIST+// mediaextensions.analytics.*: BrowseChangeEvent/ErrorEvent/MediaClickedEvent/+//   ViewChangeEvent/VisibleItemsEvent + client.AnalyticsCallback/Parser/RootHintsPopulator+```++---++## 8. Messaging apps (`MESSAGING`)++Manifest: `androidx.car.app.category.MESSAGING` (`@ExperimentalCarApi`).+Messaging support also declared via an `IntentService` intent-filter:++```xml+<service android:name=".MessagingService">+  <intent-filter>+    <action android:name="androidx.car.app.messaging.action.HANDLE_CAR_MESSAGING" />+  </intent-filter>+</service>+```++There is **no** `MessagingManager`, **no** `MessagingTemplate`, **no** `RemoteInput` wrapper.+App implements `ConversationCallback`; host invokes via `ConversationCallbackDelegate`.+Lists use `ConversationItem` inside `ListTemplate` / `SectionedItemTemplate`.+Notifications use `CarNotificationManager` + `CarAppExtender` (see §12).++```java+// messaging.MessagingServiceConstants (@RequiresCarApi(8))+ACTION_HANDLE_CAR_MESSAGING = "androidx.car.app.messaging.action.HANDLE_CAR_MESSAGING";++// messaging.model.ConversationItem (@RequiresCarApi(7) implements Item)+// allowed by RowListConstraints alongside Row/Banner+getId()/getTitle()/getSelf() (name+key required)/getIcon()/isGroupConversation() (3+ vs 1:1)/+// getMessages() (oldest→newest, non-empty)/getConversationCallbackDelegate()/+// getActions()/isIndexable() (API 8);+new ConversationItem.Builder(String id, CarText title, Person self,+                             List<CarMessage> messages, ConversationCallback cb)+  .setId/setTitle/setIcon/setSelf/setGroupConversation/setMessages/setConversationCallback+  .addAction(Action) // max 1, ACTIONS_CONSTRAINTS_CONVERSATION_ITEM (TYPE_CUSTOM icon-required)+  .setIndexable(boolean).build();++// messaging.model.CarMessage (@RequiresCarApi(7))+getSender() (null|self = self-sent; else name+key)/getBody()/+// getMultimediaMimeType()+getMultimediaUri() (both or neither)/+// getReceivedTimeEpochMillis()/isRead();+new CarMessage.Builder()+  .setSender(Person|null).setBody(CarText|null)+  .setMultimediaMimeType(String).setMultimediaUri(Uri)+  .setReceivedTimeEpochMillis(long).setRead(boolean).build();++// messaging.model.ConversationCallback — host→client+void onMarkAsRead(); void onTextReply(String replyText);+// messaging.model.ConversationCallbackDelegate (@RequiresCarApi(7))+//   sendMarkAsRead(OnDoneCallback); sendTextReply(String, OnDoneCallback)+// (+ ConversationCallbackDelegateImpl, PersonsEqualityHelper.kt)+```++---++## 9. Calling / Dialer apps (`CALLING`)++Manifest: `androidx.car.app.category.CALLING` (`@ExperimentalCarApi`).+There is **no** `DialerManager` / `CallingManager` — only templates + keypad callback.++```java+// dialer.InCallTemplate implements Template (@ExperimentalCarApi)+getHeader()/getIcon()/getTitle()/getTexts()/getActions()/isLoading();+new InCallTemplate.Builder()+  .setTitle(CarText|CharSequence TEXT_ONLY).setIcon(CarIcon DEFAULT)+  .setHeader(Header) // start → ACTION_CONSTRAINTS_IN_CALL_HEADER (max 1 APP_ICON/BACK/CUSTOM icon, no click)+  .addText(CarText|CharSequence) // max MAX_TEXTS_SIZE=2, TEXT_AND_ICON+  .addAction(Action)             // max 5, IN_CALL_CONTENT (TYPE_CUSTOM icon 0-titles, max 1 FLAG_PRIMARY)+  .setLoading(boolean).build();  // content xor loading++// dialer.TelephoneKeypadTemplate implements Template (@ExperimentalCarApi)+// Keys KEY_ZERO..KEY_NINE=0..9, KEY_STAR=10, KEY_POUND=11+getHeader()/getPhoneNumber() (editable, reset on refresh)/getPrimaryAction() (call/hangup)/+// getTelephoneKeypadCallbackDelegate()/getPhoneNumberChangedDelegate()/getKeySecondaryTexts();+new TelephoneKeypadTemplate.Builder(Action primaryAction, PhoneNumberChangeListener l)+  // primary: TELEPHONE_KEYPAD_PRIMARY (max 1 TYPE_CUSTOM icon 0-titles)+  .setHeader(Header) // TELEPHONE_KEYPAD_HEADER (max 1 APP_ICON/BACK)+  .setPhoneNumber(String|null).setTelephoneKeypadCallback(TelephoneKeypadCallback|null)+  .addKeySecondaryText(@KeypadKey int, CarText TEXT_AND_ICON).setKeySecondaryTexts(Map).build();++// dialer.TelephoneKeypadCallback (@ExperimentalCarApi)+void onKeyDown(@KeypadKey int key); void onKeyUp(@KeypadKey int key); // once per gesture, no repeat+void onKeyLongPress(@KeypadKey int key); // down → longPress → up+// dialer.TelephoneKeypadCallbackDelegate/Impl+// PhoneNumberChangeListener.onPhoneNumberChanged(String) — backspace updates without keypad event+```++---++## 10. Weather apps (`WEATHER`)++Manifest: `androidx.car.app.category.WEATHER` (API 7).+No dedicated weather manager/template — compose from shared templates:++- `ListTemplate` / `SectionedItemTemplate` (forecast rows: `Row` + `CarIcon` + `DistanceSpan`/`DurationSpan`)+- `GridTemplate` (`GridItem` per day/hour, `setItemSize/setItemImageShape` API 8)+- `TabTemplate` (Current | Hourly | Daily; `TabStyle` API 9)+- `PaneTemplate` (alert detail), `MessageTemplate` (no data), `PlaceListMapTemplate`+  (radar city list; `MAP_TEMPLATES`)+- `Header` + `CarText` variants; `CarProgressBar` (precipitation chance, API 9)++---++## 11. IoT apps (`IOT`)++Manifest: `androidx.car.app.category.IOT` (API 6).+No `IoTManager` — manifest-only category. Compose from:++- `GridTemplate` (device grid), `ListTemplate` (`Row` + `Toggle` for switches),+  `SectionedItemTemplate` (`RowSection` per room + `ChipSection` filters, API 9),+  `PaneTemplate` (device detail), `MessageTemplate` (offline),+  `SignInTemplate` (account link), `SearchTemplate` (device search)+- `Row.Builder.setToggle(Toggle)`; `Action` with `ParkedOnlyOnClickListener` where required++---++## 12. Settings / sign-in / search / suggestions / notifications++### 12.1 Settings++Manifest: `androidx.car.app.category.SETTINGS` (API 6).+Templates: `ListTemplate`, `PaneTemplate`, `MessageTemplate`, `SignInTemplate`,+`LongMessageTemplate` (parked-only ToS).++### 12.2 `model.signin.SignInTemplate` (parked-only, API 2)++```java+isLoading()/getTitle()/getHeaderAction()/getInstructions()/getAdditionalText()/+getActionStrip()/getActions()/getSignInMethod():SignInMethod (marker);+new SignInTemplate.Builder(SignInMethod m)+  .setLoading(...).setHeaderAction(APP_ICON|BACK).setActionStrip(SIMPLE max 2/1-titled)+  .addAction(Action) // max 2 BODY_WITH_PRIMARY_ACTION, MUST ParkedOnlyOnClickListener+  .setTitle(CharSequence TEXT_ONLY).setInstructions(CharSequence TEXT_WITH_COLORS)+  .setAdditionalText(CharSequence CLICKABLE_TEXT_ONLY).build();++// ProviderSignInMethod(Action action TYPE_CUSTOM + ParkedOnlyOnClickListener)+// PinSignInMethod(CharSequence pin 1..MAX_PIN_LENGTH=12)+// QRCodeSignInMethod(Uri uri) (API 4)+// InputSignInMethod: INPUT_TYPE_DEFAULT=1/PASSWORD=2; KEYBOARD_DEFAULT=1/EMAIL=2/PHONE=3/NUMBER=4+//   getHint()/getDefaultValue()/getErrorMessage()/getInputType()/getKeyboardType()/+//   getInputCallbackDelegate()/isShowKeyboardByDefault();+//   new InputSignInMethod.Builder(InputCallback cb).setHint/setDefaultValue/+//     setInputType/setErrorMessage(≤2 lines)/setKeyboardType/setShowKeyboardByDefault.build()+// InputCallback: onInputSubmitted/onInputTextChanged (both default no-op, API 2)+```++### 12.3 Search (POI / media / messaging shared)++`model.SearchTemplate`: refresh-friendly (typing changes not counted).+`Builder(SearchCallback)` + `setHeaderAction(APP_ICON|BACK)` ++`setActionStrip(SIMPLE max 2/1-titled)` + `setInitialSearchText` ++`setSearchHint` (hidden while initial text) + `setLoading` ++`setItemList(ItemList ROW_LIST_CONSTRAINTS_SIMPLE: CONTENT_LIMIT_TYPE_LIST, not selectable,+ROW_CONSTRAINTS_SIMPLE max 2 texts, image+toggle allowed, no Toggle)` ++`setShowKeyboardByDefault` (default true).++`model.SearchHeader` (API 9 exp): same but for `SectionedItemTemplate`+(mutually exclusive with `Header`).++### 12.4 `suggestion.SuggestionManager` (API 5, `SUGGESTION_SERVICE`)++```java+SuggestionManager s = carContext.getCarService(SuggestionManager.class);+s.updateSuggestions(List<Suggestion> list); // @MainThread; HostException if not nav-manifest+// suggestion.model.Suggestion (@CarProtocol)+getIdentifier()/getTitle()/getSubtitle()/getIcon() (128×128dp)/getAction():PendingIntent;+new Suggestion.Builder().setIdentifier/setTitle/setSubtitle/setAction(required)/setIcon/build();+```++### 12.5 `notification.*` (all app types)++```java+// notification.CarNotificationManager — wrapper over NotificationManagerCompat+static CarNotificationManager from(Context ctx);+notify(int, NotificationCompat.Builder) / notify(String,int,Builder)+//   auto-extends with CarAppExtender if missing; automotive unwraps extender+cancel(int)/cancel(String,int)/cancelAll();+areNotificationsEnabled(); getImportance();+createNotificationChannel(ChannelCompat)/createNotificationChannelGroup/+createNotificationChannels/createNotificationChannelGroups/+deleteNotificationChannel/deleteNotificationChannelGroup/deleteUnlistedNotificationChannels/+getNotificationChannel(String[,conversationId])/getNotificationChannelGroup/+getNotificationChannels()/getNotificationChannelGroups();+static getEnabledListenerPackages(Context);++// notification.CarAppExtender implements NotificationCompat.Extender — MUST extend or not shown on car+// HUN if IMPORTANCE_HIGH/PRIORITY_HIGH+; badge if DEFAULT+; TBT nav if ongoing+CATEGORY_NAVIGATION+// (suppressed if not active nav or already in nav template; setOnlyAlertOnce(true) recommended)+extend(NotificationCompat.Builder|Notification.Builder);+static boolean isExtended(Notification n);+getContentTitle/Text(); getSmallIcon():@DrawableRes; getLargeIcon():Bitmap|null;+getContentIntent()/getDeleteIntent():PendingIntent|null; getActions(); getImportance();+getColor():CarColor|null (nav HUN only); getChannelId():String|null (AAOS only);+new CarAppExtender.Builder()+  .setContentTitle/setContentText/setSmallIcon(int)/setLargeIcon(Bitmap)/+  setContentIntent/setDeleteIntent/addAction(int,title,PendingIntent)|addAction(Action) (max 2)/+  setImportance(int AA only)/setColor(CarColor nav only)/setChannelId(String AAOS only).build();++// notification.CarPendingIntent + CarAppNotificationBroadcastReceiver+static PendingIntent getCarApp(Context ctx, int reqCode, Intent intent, int flags);+// validates: ACTION_NAVIGATE geo: | ACTION_DIAL/ACTION_CALL tel: | own CarAppService;+// strips IMMUTABLE→mutable (+ALLOW_UNSAFE_IMPLICIT_INTENT on U+);+// automotive → getActivity(CarAppActivity); projected → getBroadcast(CarAppNotificationBroadcastReceiver)+```++### 12.6 Cluster (`FEATURE_CLUSTER`, API 6)++Manifest: `androidx.car.app.category.FEATURE_CLUSTER` with+`SessionInfo.DISPLAY_TYPE_CLUSTER`. Only `NavigationTemplate` is allowed;+feed it via the same `NavigationManager.updateTrip(Trip)` cluster path.++### 12.7 Theming (API 9, all app types)++```java+// opt-in: override CarAppService.getCarAppThemeSource()+//   THEME_SOURCE_SYSTEM (default, OEM styling) vs THEME_SOURCE_APP (brand styling, CAL defaults)+// manifest: <meta-data android:name="androidx.car.app.theme" .../> (also permission-UI drawables)+// styles: TabStyle / BannerStyle / MediaPlaybackStyle / CarIconStyle.setShape(Shape) /+//         Background / Shape / CarProgressBar — see §3.3; host may enforce contrast + fallback+```++---++## 13. Vehicle hardware (all app types, API-gated)++### 13.1 `hardware.CarHardwareManager` (API 3, `HARDWARE_SERVICE`)++```java+CarHardwareManager hw = carContext.getCarService(CarHardwareManager.class);+CarInfo getCarInfo(); CarSensors getCarSensors();+@ExperimentalCarApi CarClimate getCarClimate();+// static create(CarContext, HostDispatcher) resolves impl via+// CarAppMetadataHolderService.CAR_HARDWARE_MANAGER metadata;+// throws if host < LEVEL_3 or missing app-automotive|app-projected dep.+```++### 13.2 `hardware.common.*`++```java+// CarValue<T> (API 3) — STATUS_UNKNOWN=0/SUCCESS=1/UNIMPLEMENTED=2/UNAVAILABLE=3+T getValue(); long getTimestampMillis(); // elapsedRealtime base+int getStatus(); List<CarZone> getCarZones();+// sentinels: UNKNOWN_INTEGER/BOOLEAN/FLOAT/STRING/LIST/ARRAY, UNIMPLEMENTED_INTEGER/FLOAT_LIST+// CarUnit — CarDistanceUnit{MILLIMETER=1,METER=2,KILOMETER=3,MILE=4},+//   CarSpeedUnit{METERS_PER_SEC=101,KILOMETERS_PER_HOUR=102,MILES_PER_HOUR=103},+//   CarVolumeUnit{MILLILITER=201,LITER=202,US_GALLON=203,IMPERIAL_GALLON=204} (exp)+// CarZone (API 5) — rows ROW_ALL/FIRST/SECOND/THIRD/EXCLUDE_FIRST,+//   cols COLUMN_ALL/LEFT/CENTER/RIGHT/DRIVER/PASSENGER, CAR_ZONE_GLOBAL+//   getRow/getColumn; Builder.setRow/setColumn.build()+// OnCarDataAvailableListener<T>.onCarDataAvailable(T)+// CarSetOperationStatusCallback (API 5) — OPERATION_STATUS_SUCCESS/+//   FEATURE_UNIMPLEMENTED/UNSUPPORTED/TEMPORARILY_UNAVAILABLE/SETTING_NOT_ALLOWED/+//   UNSUPPORTED_VALUE/INSUFFICIENT_PERMISSION/ILLEGAL_CAR_HARDWARE_STATE/UPDATE_TIMEOUT+//   + onSetCarClimateState{...}(int) per climate feature+```++### 13.3 `hardware.info.*`++```java+// CarInfo (API 3)+fetchModel/fetchEnergyProfile/fetchExteriorDimensions(Executor, OnCarDataAvailableListener) // dims API 7+add/removeTollListener; add/removeEnergyLevelListener; add/removeSpeedListener;+add/removeMileageListener; add/removeEvStatusListener (exp);+// CarSensors (API 3) — UPDATE_RATE_NORMAL=1/UI=2/FASTEST=3+add/removeAccelerometerListener; add/removeGyroscopeListener; add/removeCompassListener;+add/removeCarHardwareLocationListener(int rate, Executor, OnCarDataAvailableListener);+// Model — getName/getYear/getManufacturer():CarValue+// EnergyProfile — EvConnectorType{UNKNOWN/J1772/MENNEKES/CHADEMO/COMBO_1/COMBO_2/+//   TESLA_ROADSTER/HPWC/SUPERCHARGER/GBT/GBT_DC/SCAME/OTHER=101},+//   FuelType{UNKNOWN/UNLEADED/LEADED/DIESEL_1/DIESEL_2/BIODIESEL/E85/LPG/CNG/LNG/ELECTRIC/HYDROGEN/OTHER}+// EnergyLevel — getBatteryPercent/getFuelPercent/getEnergyIsLow/getRangeRemainingMeters,+//   getDistanceDisplayUnit(), getFuelVolumeDisplayUnit() (exp)+// Speed — getRawSpeedMetersPerSecond/getDisplaySpeedMetersPerSecond/getSpeedDisplayUnit()+// Mileage — getOdometerInKilometers() (+@Deprecated getOdometerMeters alias)+// EvStatus (exp) — getEvChargePortOpen/getEvChargePortConnected+// TollCard.getCardState(); ExteriorDimensions (API 7, needs android.car.permission.CAR_INFO)+// Accelerometer/Gyroscope/Compass (float-list vectors); CarHardwareLocation (UNIMPLEMENTED_LOCATION)+```++### 13.4 `hardware.climate.*` (API 5, experimental)++```java+// CarClimate+registerClimateStateCallback(Executor, RegisterClimateStateRequest, CarClimateStateCallback);+unregisterClimateStateCallback(CarClimateStateCallback);+fetchClimateProfile(Executor, ClimateProfileRequest, CarClimateProfileCallback);+setClimateState<E>(Executor, ClimateStateRequest<E>, CarSetOperationStatusCallback);+// ClimateProfileRequest / RegisterClimateStateRequest features:+//   FEATURE_HVAC_POWER=1/AC=2/MAX_AC=3/CABIN_TEMPERATURE=4/FAN_SPEED=5/FAN_DIRECTION=6/+//   SEAT_TEMPERATURE_LEVEL=7/SEAT_VENTILATION_LEVEL=8/STEERING_WHEEL_HEAT=9/+//   RECIRCULATION=10/AUTO_RECIRCULATION=11/AUTO_MODE=12/DUAL_MODE=13/+//   DEFROSTER=14/MAX_DEFROSTER=15/ELECTRIC_DEFROSTER=16/CAR_ZONE_MAPPING=17+// CarClimateFeature/Builder(feature).addCarZones(CarZone...)+// ClimateStateRequest<T>: getRequestedFeature/getCarZones/getRequestedValue+// CarClimateStateCallback + CarClimateProfileCallback — onHvacPower/Ac/MaxAcMode/+//   CabinTemperature/FanSpeedLevel/FanDirection/SeatTemperatureLevel/SeatVentilationLevel/+//   SteeringWheelHeat/HvacRecirculation/HvacAutoRecirculation/HvacAutoMode/HvacDualMode/+//   Defroster/MaxDefroster/ElectricDefroster[StateAvailable](CarValue<...>) (all default {})+// Profiles: HvacPower/Ac/MaxAc/Recirculation/AutoRecirculation/AutoMode/DualMode/+//   Defroster/MaxDefroster/ElectricDefroster/CabinTemperature (ranges+increments+zone maps)/+//   FanSpeedLevel/FanDirection/SeatTemperature/SeatVentilation/SteeringWheelHeat/CarZoneMappingInfo+```++---++## 14. Automotive-only vs Projected-only++| Capability | `app-automotive` | `app-projected` |+|---|---|---|+| `CarInfo/Sensors` | `AutomotiveCarInfo/Sensors` via `android.car` + `PropertyManager` | `ProjectedCarInfo/Sensors` via `CarHardwareHostDispatcher` → host |+| `CarClimate` | `AutomotiveCarClimate` supported | unsupported (throws) |+| UI host | `CarAppActivity/BaseCarAppActivity/LauncherActivity + TemplateSurfaceView` natively | phone renders via projected host (AA/CP); no activity in lib |+| Connection | `AutomotiveCarConnectionTypeLiveData = NATIVE` | `CarConnectionTypeLiveData` provider + broadcast (`PROJECTION`) |+| Result | `ResultManagerAutomotive` (real `setActivityResult`) | base `ResultManager` (AA: no-op / null caller) |+| Audio | `AutomotiveCarAudioRecord` | `ProjectedCarAudioRecord` |+| Wiring | `CAR_HARDWARE_MANAGER=AutomotiveCarHardwareManager` | `CAR_HARDWARE_MANAGER=ProjectedCarHardwareManager` |++### 14.1 Automotive activities (`app-automotive/activity.*`)++```java+// activity.CarAppActivity extends BaseCarAppActivity — automotive-only entry+//   ACTION_RENDER="android.car.template.host.RendererService"+//   onCreate → bindToViewModel(new SessionInfo(DISPLAY_TYPE_MAIN, intent.identifier))+// activity.BaseCarAppActivity extends FragmentActivity+//   bindToViewModel(SessionInfo); getServiceComponentName()/retrieveServiceComponentName()+//   (queries SERVICE_INTERFACE in own package; exactly 1 required)+//   ICarAppActivity.Stub{setSurfacePackage/registerRendererCallback/setInsetsListener/+//     setSurfaceListener/onStartInput/onStopInput/startCarApp/finishCarApp/onUpdateSelection/showAssist}+//   insets fan-out; takeSurfaceSnapshot() via PixelCopy;+//   state IDLE/CONNECTING/CONNECTED/ERROR (TemplateSurfaceView/ErrorMessageView/LoadingView)+// activity.LauncherActivity (@ExperimentalCarApi) — FEATURE_AUTOMOTIVE ? CarAppActivity : MAIN/DEFAULT+// activity.ActivityLifecycleDelegate — registerRendererCallback(IRendererCallback) →+//   ServiceDispatcher.dispatch(ON_CREATE/START/RESUME/PAUSE/STOP/DESTROY)+// activity.ServiceDispatcher — dispatch(String,OneWayCall)/fetch(...)+//   DeadObject→HOST_CONNECTION_LOST, Remote→HOST_ERROR, Bundler→CLIENT_SIDE_ERROR+// activity.HostUpdateReceiver — PACKAGE_REPLACED → CarAppViewModel.onHostUpdated()+// activity.ResultManagerAutomotive — setCarAppResult→ViewModel; getCallingComponent (AA: null)+// + CarAppViewModel/Factory/ServiceConnectionManager/ErrorHandler/LogTags,+//   ui.ErrorMessageView/LoadingView,+//   renderer.surface.TemplateSurfaceView/SurfaceWrapper/Provider/HolderListener/+//     ControlCallback/LegacySurfacePackage/OnBackPressed/OnCreateInputConnection/RemoteProxyInputConnection+//   renderer.ICarAppActivity/IRendererCallback/IRendererService/ISurfaceListener/IInsetsListener+// hardware.AutomotiveCarHardwareManager + climate/info/common (PropertyManager,+//   CarPropertyProfile<T> (HvacFanDirection…), CarPropertyResponse, GetPropertyRequest,+//   PropertyIdAreaId, PropertyRequestProcessor, PropertyResponseCache, PropertyUtils,+//   CarValueUtils, OnCarPropertyResponseListener, CarInternalError, CarZone*Converter/Utils)+// media.AutomotiveCarAudioRecord+// Automotive manifest:+//   <activity android:name="androidx.car.app.activity.CarAppActivity" android:exported="true"+//     android:launchMode="singleTask" android:label="...">+//     <intent-filter><action android:name="android.intent.action.MAIN" />+//     <category android:name="android.intent.category.LAUNCHER" /></intent-filter>+//     <meta-data android:name="distractionOptimized" android:value="true" />+//   </activity>+```++### 14.2 Projected (`app-projected/*`)++```java+// hardware.ProjectedCarHardwareManager implements CarHardwareManager (@RestrictTo(LIBRARY) @CarProtocol)+//   getCarInfo():ProjectedCarInfo; getCarSensors():ProjectedCarSensors;+//   NO getCarClimate() (UnsupportedOperationException); ctor (CarContext, HostDispatcher)+// hardware.common.CarHardwareHostDispatcher (+CarResultStub/Map) — host-IPC fan-out+// hardware.info.ProjectedCarInfo / ProjectedCarSensors — host-dispatched+// media.ProjectedCarAudioRecord+// No activities, no renderer/, no PropertyManager/CarPropertyProfile, no AutomotiveCar*+```++---++## 15. Testing surface++`app-testing` (`androidx.car.app.testing.*`, `testing.navigation.*`).+**No `CarAppTestRule`** in this drop — compose the fakes directly:++```java+TestCarContext.create(); // fake CarContext + service overrides+TestScreenManager / ScreenController  // drive Screen.onGetTemplate/invalidate + lifecycle+SessionController                     // drive Session.onCreateScreen/onNewIntent/lifecycle+TestAppManager / navigation.TestNavigationManager // record invalidate/navigationStarted/…+FakeHost // stub ICarHost+TestOnDoneCallbackStub, TestLifecycleOwner, TestDelegateInvoker.kt+```++---++## 16. Permissions, constraints, quotas++### Permissions (`androidx.car.app.CarAppPermission`)++| Permission | Needed for |+|---|---|+| `androidx.car.app.ACCESS_SURFACE` | `AppManager.setSurfaceCallback` / custom map |+| `androidx.car.app.NAVIGATION_TEMPLATES` | `NavigationTemplate`, legacy nav templates, nav side of `MapWithContentTemplate` |+| `androidx.car.app.MAP_TEMPLATES` | `PlaceListMapTemplate`, map side of `MapWithContentTemplate` (self-drawn nav maps exempt) |+| `androidx.car.app.MEDIA_TEMPLATES` | media templates (triggers API 9 1-FAB limit) |++```java+static boolean checkHasPermission(Context ctx, String perm);+static boolean checkHasLibraryPermission(Context ctx, @LibraryPermission String perm);+```++Platform-adjacent: `android.car.permission.CAR_INFO` (exterior dims etc.);+vehicle-property read perms in `PropertyManager.checkPermissions()`+(`CAR_INFO / CAR_EXTERIOR_ENVIRONMENT / CAR_ENERGY / CAR_SPEED / READ_*`);+host-side `android.car.permission.TEMPLATE_RENDERER` (auto API 31+);+`RECORD_AUDIO` for `CarAudioRecord`; location for current-location.++### Constraints (`model.constraints.*`, all `@RestrictTo(LIBRARY)`)++- `ActionsConstraints`: `HEADER`(1 icon, no click) / `MULTI_HEADER`(2) / `BODY`(2/2-titled+  `COLOR_ONLY`) / `BODY_WITH_PRIMARY_ACTION`(1 primary) / `SIMPLE`(strip 2/1-titled+  `TEXT_ONLY`) / `NAVIGATION`(map strips 4/4-titled/1-primary `TEXT_AND_ICON`) /+  `MAP`(4/1-primary icon-only) / `ROW`(2 `CUSTOM/MEDIA_PLAYBACK`, 1 primary) /+  `CONVERSATION_ITEM`(1 `CUSTOM` icon) / `FAB`(2 `CUSTOM/COMPOSE_MESSAGE/MEDIA_PLAYBACK`+  icon+bg; media 1 on API 9+) / `TABS`(needs `APP_ICON`) / `TAB_ACTIONS`(1 custom icon) /+  `IN_CALL_HEADER`(1 `APP_ICON/BACK/CUSTOM`) / `IN_CALL_CONTENT`(5 custom 0-titled 1-primary) /+  `TELEPHONE_KEYPAD_HEADER`(1 `APP_ICON/BACK`) / `TELEPHONE_KEYPAD_PRIMARY`(1 custom icon) /+  `BANNER_TRAILING`(2) / `BANNER_BELOW`(3/2-titled) — via `validateOrThrow(List<Action>)`.+- `RowListConstraints`: `CONSERVATIVE` / `PANE` / `SIMPLE` / `MAP_ROW_LIST_CONSTRAINTS_ALLOW_SELECTABLE`+  (+`ROUTE_PREVIEW` alias) / `FULL_LIST`; allows `Row|ConversationItem|Banner`.+- `RowConstraints`: `UNCONSTRAINED / CONSERVATIVE / PANE / SIMPLE / FULL_LIST`.+- `CarTextConstraints`: `CONSERVATIVE`(none) / `UNCONSTRAINED` /+  `CLICKABLE_TEXT_ONLY` / `COLOR_ONLY`(FgColor) / `TEXT_ONLY`(Distance/Duration/Timer) /+  `TEXT_AND_ICON` / `TEXT_WITH_COLORS` / `TEXT_WITH_COLORS_AND_ICON`.+- `CarIconConstraints`: `UNCONSTRAINED`(bitmap/resource/uri-content) /+  `DEFAULT`(bitmap/resource only; URI must be `content:`).+- `ModelUtils`: `validateAllNonBrowsableRowsHaveDistance` (PlaceListMap),+  `validateAllRowsHaveDistanceOrDuration` (route preview),+  `validateAllRowsHaveOnlySmallImages` (no LARGE), `validateNoRowsHaveBothMarkersAndImages`.+- `navigation.model.constraints.ContentTemplateConstraints`:+  `MAP_WITH_CONTENT_TEMPLATE_CONSTRAINTS` (API 7 Grid/Message/List/Pane),+  `..._API_8` (+SectionedItem).+- `constraints.ConstraintManager` (API 2): `CONTENT_LIMIT_TYPE_LIST=0/GRID=1/+  PLACE_LIST=2/ROUTE_LIST=3/PANE=4`; `getContentLimit(type)` (host or+  `R.integer.content_limit_*` fallback); `isAppDrivenRefreshEnabled()` (API 6).+- Template flow (`Screen`): 5-task quota; refresh vs push rules in §2.2;+  `ListTemplate` truncates to 100; `MAX_MESSAGES_PER_CONVERSATION=10`.++---++## Appendix A: 1.9.0-alpha02 + alpha01 changelog++**`1.9.0-alpha02` (Sept 2026)** — theming + search + styling release:++- App theming: `CarAppThemeSource` + `CarAppService.onGetAppTheme` (+ IPC) — apps opt into+  brand theming, hosts query preferred config.+- Search header: `SearchHeader` for `SectionedItemTemplate` (API 9 search replacement).+- Component styling: `TabStyle` (bg/content/corner radii), `BannerStyle` (shape/corners),+  `MediaPlaybackStyle` + `setMediaAccentColor` + standalone `StrokeCap`, `CarProgressBarStyle`+  (nullable colours; deprecated colour methods removed from `CarProgressBar`).+- Tabs: custom bg/content/text colours + corner radii.+- Icons/images: `IMAGE_TYPE_ICON` deprecated across `Row/GridItem/Banner/CondensedItem`+  → `IMAGE_TYPE_SMALL/MEDIUM` (untinted default); `CarIconStyle` rework + custom `Shape` on `CarIcon`.+- Banners: `BannerStyle` shapes/corners, `IMAGE_TYPE_SMALL/LARGE` variants, deprecated+  icon/bg APIs removed → `setLeadingImage/addTrailingImage`.+- Headers/layout: `SearchHeader` (API 9), `startHeaderImage` on `Header`,+  `incompleteLastRowStrategy` for grid/condensed/spotlight partial rows.+- Bug fix: `Action.TYPE_MEDIA_PLAYBACK` ignored as template FAB on Car API 9+ hosts.++**`1.9.0-alpha01` (May 2026)** — content-flexibility release:++- `Banner` + `BannerSection` for `SectionedItemTemplate`.+- `NavigationManager.setVoiceAssistantCapabilities` + `NavigationVoiceAssistantCapabilities`+  (voice actions/disruptions/consent → host).+- `CarAppApiLevel` 9.+- `Chip`/`ChipSection` shape via `ChipStyle`.+- `CondensedItem`/`CondensedSection` high-density layouts.+- Experimental `Header` subtitles + `Background` model.+- Spotlight section (hero image + condensed items), minimized control panel (NPV),+  section headers (titles/overlines/brand icons/trailing actions), expanded header layout+  (collapsing background image + secondary actions).++---++## Appendix B: Full class index++All FQCNs are `androidx.car.app.*` unless noted; `(P)` = `app-projected`,+`(A)` = `app-automotive`, `(T)` = `app-testing`.++**Core:** `CarAppService`, `CarAppBinder`, `Session`, `Screen`, `ScreenManager`,+`CarContext`, `AppManager`, `SurfaceCallback`, `SurfaceContainer`, `CarToast`,+`CarAppPermission`, `HostInfo`, `HandshakeInfo`, `AppInfo`, `SessionInfo`,+`SessionInfoIntentEncoder`, `CarAppMetadataHolderService`, `MainThread`/`Manager`/+`ManagerFactory`/`ManagerCache` (`managers.*`), `ResultManager` (`managers.*`),+`validation.HostValidator`, `versioning.CarAppApiLevel(s)`,+`annotations.{RequiresCarApi,ExperimentalCarApi,CarProtocol,KeepFields}`,+`features.CarFeatures`, `connection.{CarConnection,CarConnectionTypeLiveData,+AutomotiveCarConnectionTypeLiveData}`, `constraints.ConstraintManager`,+`suggestion.SuggestionManager`, `suggestion.model.Suggestion`,+`serialization.*`, `utils.*`.++**Model (`model.*`):** `Template`, `TemplateInfo`, `TemplateWrapper`, `Action`,+`ActionStrip`, `Header`, `SearchHeader` (9), `Tab`, `TabContents`, `TabStyle` (9),+`Pane`, `PaneTemplate`, `ListTemplate`, `SectionedItemTemplate` (8),+`GridTemplate`, `MessageTemplate`, `LongMessageTemplate` (2), `SearchTemplate`,+`SearchCallback`, `PlaceListMapTemplate`, `TabTemplate` (6),+`Item`, `ItemList`, `SectionedItemList`, `Section`, `SectionHeader`,+`RowSection`, `GridSection` (8), `ChipSection` (9), `CondensedSection` (9),+`SpotlightSection` (8/9), `BannerSection` (9), `Row`, `GridItem`,+`CondensedItem`, `Chip`, `ChipStyle`, `Banner`, `BannerElement`, `BannerStyle` (9),+`Toggle`, `Metadata`, `Place`, `PlaceMarker`, `CarLocation`, `Alert` (5),+`AlertCallback` (5), `AlertCallbackDelegate` (5), `CarText`, `CarSpan`,+`DistanceSpan`, `DurationSpan`, `ForegroundCarColorSpan`, `CarIconSpan`,+`ClickableSpan`, `TimerSpan`, `Distance`, `DateTimeWithZone`, `CarColor`,+`CarIcon`, `CarIconStyle`, `Background` (9), `Shape` (9), `CarProgressBar` (9),+`CarProgressBarStyle`, `StrokeCap`, `OnClickListener`,+`ParkedOnlyOnClickListener`, `InputCallback`, `OnContentRefreshListener`,+`constraints.{ActionsConstraints,RowConstraints,RowListConstraints,+CarTextConstraints,CarIconConstraints,TabsConstraints,TabContentsConstraints}`,+`ModelUtils`, `model.signin.{SignInTemplate,SignInMethod,ProviderSignInMethod,+PinSignInMethod,QRCodeSignInMethod,InputSignInMethod}`.++**Navigation (`navigation.*`):** `NavigationManager`, `NavigationManagerCallback`,+`navigation.model.{NavigationTemplate,MapWithContentTemplate (7),MapTemplate (5,dep),+PlaceListNavigationTemplate (dep),RoutePreviewNavigationTemplate (dep),Trip,Step,+TravelEstimate,Destination,RoutingInfo,MessageInfo,Maneuver,Lane,LaneDirection,+MapController (5),PanModeListener,PanModeDelegate,PanModeDelegateImpl,+NavigationVoiceAssistantCapabilities (9),+constraints.ContentTemplateConstraints}`.++**Media (`media.*`, `media.model.*`, `mediaextensions.*`):**+`MediaPlaybackManager` (8), `MediaPlaybackTemplate` (8, `media.model`),+`MediaPlaybackStyle` (9), `MediaConstants`, `CarAudioRecord` (5),+`CarAudioCallback`, `OpenMicrophoneRequest/Response`, `CarAudioCallbackDelegate`,+`AutomotiveCarAudioRecord` (A), `ProjectedCarAudioRecord` (P),+`MediaBrowserExtras`, `MediaIntentExtras`, `MetadataExtras`,+`mediaextensions.analytics.{Constants,ThreadUtils,client.*,event.*}`.++**Messaging / notifications:** `messaging.MessagingServiceConstants` (8),+`messaging.model.{ConversationItem (7),CarMessage (7),ConversationCallback,+ConversationCallbackDelegate}`, `notification.{CarNotificationManager,+CarAppExtender,CarPendingIntent,CarAppNotificationBroadcastReceiver}`.++**Dialer (`dialer.*`):** `InCallTemplate`, `TelephoneKeypadTemplate`,+`TelephoneKeypadCallback`, `TelephoneKeypadCallbackDelegate` (all experimental).++**Hardware (`hardware.*`):** `CarHardwareManager`,+`common.{CarValue,CarUnit,CarZone (5),OnCarDataAvailableListener,+CarSetOperationStatusCallback (5)}`,+`info.{CarInfo,CarSensors,Model,EnergyProfile,EnergyLevel,Speed,Mileage,+EvStatus,TollCard,ExteriorDimensions (7),Accelerometer,Gyroscope,Compass,+CarHardwareLocation}`, `climate.{CarClimate,ClimateProfileRequest,+CarClimateFeature,RegisterClimateStateRequest,ClimateStateRequest,+CarClimateStateCallback,CarClimateProfileCallback,Hvac*Profile,+CabinTemperatureProfile,FanSpeedLevelProfile,FanDirectionProfile,+SeatTemperatureProfile,SeatVentilationProfile,SteeringWheelHeatProfile,+CarZoneMappingInfoProfile}` (all 5, experimental),+`AutomotiveCarHardwareManager` (A), `automotive info/climate/common`+(`AutomotiveCarInfo/Sensors/Climate`, `CarPropertyProfile`, `PropertyManager`,+`CarPropertyResponse`, `GetPropertyRequest`, `PropertyIdAreaId`,+`PropertyRequestProcessor`, `PropertyResponseCache`, `PropertyUtils`,+`CarValueUtils`, `OnCarPropertyResponseListener`, `CarInternalError`,+`CarZone*Converter/Utils`) (A),+`ProjectedCarHardwareManager`, `common.CarHardwareHostDispatcher`,+`info.ProjectedCarInfo/Sensors` (P).++**Automotive activity (A):** `activity.{CarAppActivity,BaseCarAppActivity,+LauncherActivity,ActivityLifecycleDelegate,ServiceDispatcher,HostUpdateReceiver,+ResultManagerAutomotive,CarAppViewModel,CarAppViewModelFactory,+ServiceConnectionManager,ErrorHandler,LogTags,ui.ErrorMessageView/LoadingView,+renderer.surface.* (TemplateSurfaceView/SurfaceWrapper/Provider/HolderListener/+ControlCallback/LegacySurfacePackage/OnBackPressed/OnCreateInputConnection/+RemoteProxyInputConnection), renderer.ICarAppActivity/IRendererCallback/+IRendererService/ISurfaceListener/IInsetsListener}`.++**Testing (T):** `testing.{TestCarContext,TestAppManager,TestScreenManager,+ScreenController,SessionController,FakeHost,TestOnDoneCallbackStub,+TestLifecycleOwner,TestDelegateInvoker.kt,navigation.TestNavigationManager}`.
auto/build.gradle.kts
diff --git a/auto/build.gradle.kts b/auto/build.gradle.ktsindex c067c5cdd1..30c2868856 100644--- a/auto/build.gradle.kts+++ b/auto/build.gradle.kts@@ -20,6 +20,15 @@ dependencies {     // implements the host binders (ICarHost/IAppHost/INavigationHost/     // IConstraintHost) so the nav card renders whatever Maps publishes --     // its own SurfaceContainer surface plus its NavigationTemplate -- instead-    // of MA Auto re-rendering a second map. Same 1.4.0 the maps app uses.+    // of MA Auto re-rendering a second map. Tracks the carApp catalog version.     implementation(libs.androidx.car.app)+    // Compose-in-Presentation: the car display owns its own LifecycleOwner ++    // ViewModelStoreOwner + SavedStateRegistryOwner (see CarDisplayLifecycle),+    // so the Presentation hosts a ComposeView on its private virtual display.+    // Compose UI itself rides the BOM through :library:ui; these are the only+    // direct additions, scoped to this module like :library:map's own+    // lifecycle-runtime-compose (never in the shared convention plugin).+    implementation(libs.androidx.lifecycle.runtime.compose)+    implementation(libs.androidx.savedstate)+    implementation(libs.androidx.lifecycle.viewmodel.savedstate) }
auto/docs/HANDOFF.md
diff --git a/auto/docs/HANDOFF.md b/auto/docs/HANDOFF.mdindex 225cdd72d3..c896ec6a19 100644--- a/auto/docs/HANDOFF.md+++ b/auto/docs/HANDOFF.md@@ -368,11 +368,16 @@ gearhead pull plus `jadx` and the `openssl` CLI, none of which this environment  1. **Confirm the render path** — frames stream and are acked, but nobody has    confirmed they decode and display on the DHU surface yet.-2. **Input**, so the DHU's touch does something. Channel messages are mapped in FINDINGS.md.+2. **Input tap E2E** — the channel is up (binds on the DHU's service 3,+   key-binding round-trips with status 0); what remains is a real tap with+   the DHU window focused, confirming `InputEvent.Touch` increments. 3. **MAOS integration** (plan Phase 3) — the role move is the risky part. Both the    privapp-permissions entry and the `roles.xml` patch are boot-fatal if wrong, so change one    at a time and flash between.-4. Audio, sensors, then the real car UI.+4. Audio (sinks on 4/5 carry `media_sink` payloads and should work; mic moved+   to the DHU's service 7 — needs a live chunk check), then the real car UI.+   Sensors are DONE against the DHU (LOCATION/NIGHT/DRIVING subscribed,+   batches flow; other types get per-type -9, types 23-26 get bare 0xff).  Phase 3 in the plan has the full role strategy: MA Auto takes `SYSTEM_AUTOMOTIVE_PROJECTION`, MA Cast moves to `COMPANION_DEVICE_APP_STREAMING` (which@@ -410,3 +415,18 @@ Two more found from live wire capture, not decompilation:   0xff'd. And the 0x7 must be framed on the TARGET channel, not channel 0   (ch0-framed opens draw STATUS_INVALID_CHANNEL, -5). - The head unit speaks first. The phone answers a version request, it does not send one.+- **DHU 2.0 service ids do NOT match gearhead's `rro`** (verified by decoding+  the 569B 0x6 discovery payload, 2026-09-18). The DHU advertises 1-7 as:+  1=sensor (`Sensor{1,10,13}`, exactly `default.ini [sensors]`), 2=video,+  3=input (keycodes + 800x480 TouchConfig), 4/5=audio sinks, 6=vendor,+  7=mic (`MediaSourceService`). There is NO service 8. Owners bind by+  **payload type** (`hasSensorSource`/`hasInputSource`/`hasMediaSource`),+  like gearhead (`jlf.a(xpa)` reads the sensor config out of the entry) --+  never by hardcoded id. Sending sensor subscribes to the mic channel earns+  `0xff` "unexpected message", which is what the ch7 failures were.+- **`xnv` SensorResponse is status-only** (`xow`: field 1 = `xls` status, no+  type echo -- gearhead's `jcd.s` waits synchronously per subscribe). `08 00`+  = SUCCESS; `08 f7 ff..` (10-byte varint) = -9 STATUS_INVALID_SENSOR.+  Owners attribute answers FIFO in subscribe order. Our old+  `{sensor_type=1, status=2}` layout parsed every real answer as+  uninitialized → Observed.
auto/protocol/src/main/java/com/vayunmathur/auto/protocol/SensorCodec.kt
diff --git a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/SensorCodec.kt b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/SensorCodec.ktindex dcb9ce367b..4f9ee22d65 100644--- a/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/SensorCodec.kt+++ b/auto/protocol/src/main/java/com/vayunmathur/auto/protocol/SensorCodec.kt@@ -211,10 +211,14 @@ data class SensorSnapshot(     } } -/** A classified inbound ch7 message. Anything else on the channel is [Observed]. */+/** A classified inbound sensor-channel message. Anything else on the channel is [Observed]. */ sealed interface InboundSensor {-    /** The head unit answered a subscription (0x8002); [status] 0 means subscribed. */-    data class Subscribed(val type: SensorType, val status: Int) : InboundSensor+    /**+     * The head unit answered a subscription (0x8002); [status] 0 means+     * subscribed. The wire (`xnv`/`xow`) carries no sensor type -- the owner+     * attributes answers FIFO in subscribe order (see [SensorCodec]).+     */+    data class Subscribed(val status: Int) : InboundSensor      /** Streamed readings (0x8003); empty when the batch carried no events. */     data class Readings(val events: List<SensorEvent>) : InboundSensor@@ -245,9 +249,12 @@ sealed interface InboundSensor {  *  * Direction ground truth (auto/docs/FINDINGS.md section 2, the `rvb`  * endpoint): `xnu` request fields are (1 sensor_type, 2 min_update_period).- * Every other field number here is MA sender-defined -- the teardown never- * recovered the `xnv`/`xnr`/`xns` layouts -- so exact-bytes tests pin OUR- * numbering to catch an accidental renumber here, not at a DHU.+ * The `xnv` response is a bare status (`xow`: field 1 only, no type echo --+ * gearhead's `jcd.s` waits synchronously per subscribe, so answers need no+ * attribution; batched senders match FIFO in send order). Every other field+ * number here is MA sender-defined -- the teardown never recovered the+ * `xnr`/`xns` layouts -- so exact-bytes tests pin OUR numbering to catch an+ * accidental renumber here, not at a DHU.  */ object SensorCodec { @@ -267,6 +274,15 @@ object SensorCodec {      */     const val TIMEOUT_STATUS = -1 +    /**+     * Default subscribe period: gearhead's `jcd.s(xoz, long)` always writes+     * `xov` field 2, and every mined subscribe call site (`jqs`, `sbl`)+     * passes 0 (fastest rate; -1 is unsubscribe-only, see `rvp` and+     * [GalMessage.Sensor.UNSUBSCRIBE_PERIOD]). Omitting field 2 earns+     * STATUS_UNEXPECTED_MESSAGE on the DHU loopback.+     */+    const val DEFAULT_SUBSCRIBE_PERIOD_MS = 0L+     /**      * The subscription set: all 26 `xny` types in dumper order. The name is      * kept for the ch7 owner, which iterates it for subscribes and@@ -305,12 +321,17 @@ object SensorCodec {     )      /**-     * Phone -> HU: subscribe to [type]. The period is omitted for the head-     * unit's default rate -- only pass one to slow a chatty sensor down.+     * Phone -> HU: subscribe to [type]. Field 2 is always written (gearhead's+     * `jcd.s` unconditionally sets it; mined call sites pass 0): omitting it+     * earns STATUS_UNEXPECTED_MESSAGE. Pass a positive value to slow a chatty+     * sensor down, [GalMessage.Sensor.UNSUBSCRIBE_PERIOD] to unsubscribe.      */-    fun encodeSubscribe(type: SensorType, minPeriodMs: Long? = null): Pair<Int, ByteArray> {+    fun encodeSubscribe(+        type: SensorType,+        minPeriodMs: Long = DEFAULT_SUBSCRIBE_PERIOD_MS,+    ): Pair<Int, ByteArray> {         val builder = SensorRequest.newBuilder().setSensorType(type)-        if (minPeriodMs != null) builder.minUpdatePeriodMs = minPeriodMs+        builder.minUpdatePeriodMs = minPeriodMs         return GalMessage.Sensor.SENSOR_REQUEST to builder.build().toByteArray()     } @@ -338,8 +359,8 @@ object SensorCodec {     fun decodeInbound(type: Int, payload: ByteArray): InboundSensor = when (type) {         GalMessage.Sensor.SENSOR_RESPONSE -> runCatching { SensorResponse.parseFrom(payload) }             .getOrNull()-            ?.takeIf { it.isInitialized }-            ?.let { InboundSensor.Subscribed(it.sensorType, if (it.hasStatus()) it.status else 0) }+            ?.takeIf { it.hasStatus() }+            ?.let { InboundSensor.Subscribed(it.status) }             ?: InboundSensor.Observed(type)         GalMessage.Sensor.SENSOR_BATCH -> runCatching { SensorBatch.parseFrom(payload) }             .getOrNull()
auto/protocol/src/main/proto/gal/sensors.proto
diff --git a/auto/protocol/src/main/proto/gal/sensors.proto b/auto/protocol/src/main/proto/gal/sensors.protoindex 9b61a2f7e4..4ccb692b24 100644--- a/auto/protocol/src/main/proto/gal/sensors.proto+++ b/auto/protocol/src/main/proto/gal/sensors.proto@@ -62,18 +62,22 @@ enum SensorType { }  // 0x8001, phone -> HU: subscribe. `xnu` fields 1-2, from the teardown.-// Omit the period for the head unit's default rate; -1 unsubscribes (see+// Field 2 is always written (gearhead's `jcd.s` unconditionally sets it;+// mined call sites pass 0 = fastest rate); -1 unsubscribes (see // GalMessage.Sensor.UNSUBSCRIBE_PERIOD). message SensorRequest {   required SensorType sensor_type = 1;   optional int64 min_update_period_ms = 2; } -// 0x8002, HU -> phone: subscription answer. MA sender-defined: the teardown-// recovered the id but not the `xnv` layout. Status 0 means subscribed.+// 0x8002, HU -> phone: subscription answer. Teardown-exact `xnv`/`xow`:+// a single field, the `xls` status (0 = STATUS_SUCCESS, negative = per-type+// refusal, e.g. -9 STATUS_INVALID_SENSOR). There is NO sensor-type echo --+// gearhead's subscribe is synchronous (`jcd.s` waits on a semaphore per+// call), so the answer needs no attribution. Our batched subscribes match+// answers FIFO in send order (verified: the DHU answers in subscribe order). message SensorResponse {-  required SensorType sensor_type = 1;-  optional int32 status = 2;+  optional int32 status = 1; }  // 0x8003, HU -> phone: streamed readings. MA sender-defined, same caveat.
auto/protocol/src/test/java/com/vayunmathur/auto/protocol/SensorCodecTest.kt
diff --git a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/SensorCodecTest.kt b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/SensorCodecTest.ktindex 88a7eb7d2b..2391a579c5 100644--- a/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/SensorCodecTest.kt+++ b/auto/protocol/src/test/java/com/vayunmathur/auto/protocol/SensorCodecTest.kt@@ -21,15 +21,17 @@ import kotlin.test.assertTrue class SensorCodecTest {      @Test-    fun `subscribe pins sensor type in field 1 and omits the period`() {-        // `xnu`: field 1 sensor_type, field 2 min_update_period. A bare-        // LOCATION subscribe is 08 01.+    fun `subscribe pins sensor type in field 1 and gearhead's zero period in field 2`() {+        // `xnu`: field 1 sensor_type, field 2 min_update_period. Gearhead's+        // `jcd.s` always writes field 2 and the mined call sites pass 0, so+        // a bare LOCATION subscribe is 08 01 10 00.         val (type, payload) = SensorCodec.encodeSubscribe(SensorType.LOCATION)         assertEquals(GalMessage.Sensor.SENSOR_REQUEST, type)-        assertContentEquals(byteArrayOf(0x08, 0x01), payload)+        assertContentEquals(byteArrayOf(0x08, 0x01, 0x10, 0x00), payload)         val parsed = SensorRequest.parseFrom(payload)         assertEquals(SensorType.LOCATION, parsed.sensorType)-        assertTrue(!parsed.hasMinUpdatePeriodMs())+        assertTrue(parsed.hasMinUpdatePeriodMs())+        assertEquals(0L, parsed.minUpdatePeriodMs)     }      @Test@@ -100,15 +102,25 @@ class SensorCodecTest {     }      @Test-    fun `a subscription answer classifies with its status`() {-        val payload = SensorResponse.newBuilder()-            .setSensorType(SensorType.SPEED)-            .setStatus(0)+    fun `a subscription answer classifies with its status and no type`() {+        // `xnv`/`xow` is status-only (teardown-exact): `08 00` is+        // STATUS_SUCCESS with no type echo -- owners attribute FIFO.+        assertEquals(+            InboundSensor.Subscribed(0),+            SensorCodec.decodeInbound(+                GalMessage.Sensor.SENSOR_RESPONSE,+                byteArrayOf(0x08, 0x00),+            ),+        )+        // A per-type refusal is a negative status (`xls`, e.g. -9+        // STATUS_INVALID_SENSOR), still a classified answer, still typeless.+        val refused = SensorResponse.newBuilder()+            .setStatus(-9)             .build()             .toByteArray()         assertEquals(-            InboundSensor.Subscribed(SensorType.SPEED, 0),-            SensorCodec.decodeInbound(GalMessage.Sensor.SENSOR_RESPONSE, payload),+            InboundSensor.Subscribed(-9),+            SensorCodec.decodeInbound(GalMessage.Sensor.SENSOR_RESPONSE, refused),         )     } @@ -253,8 +265,9 @@ class SensorCodecTest {      @Test     fun `every subscribed type encodes its own number in field 1`() {-        // A compass subscribe is 08 02, gear is 08 08, raw EV trip is 08 1A:-        // off-by-one here subscribes the wrong sensor on a real head unit.+        // A compass subscribe is 08 02 10 00, gear is 08 08 10 00, raw EV+        // trip is 08 1A 10 00: off-by-one here subscribes the wrong sensor+        // on a real head unit.         for (type in SensorCodec.STUB_SUBSCRIPTIONS) {             val (wireType, payload) = SensorCodec.encodeSubscribe(type)             assertEquals(GalMessage.Sensor.SENSOR_REQUEST, wireType)@@ -265,7 +278,7 @@ class SensorCodecTest {             )         }         val (_, compass) = SensorCodec.encodeSubscribe(SensorType.COMPASS)-        assertContentEquals(byteArrayOf(0x08, 0x02), compass)+        assertContentEquals(byteArrayOf(0x08, 0x02, 0x10, 0x00), compass)     }      @Test
auto/src/main/AndroidManifest.xml
diff --git a/auto/src/main/AndroidManifest.xml b/auto/src/main/AndroidManifest.xmlindex c2590c967c..2d3872bb0d 100644--- a/auto/src/main/AndroidManifest.xml+++ b/auto/src/main/AndroidManifest.xml@@ -135,6 +135,7 @@     <queries>         <package android:name="com.vayunmathur.maps" />         <package android:name="com.vayunmathur.music" />+        <package android:name="com.vayunmathur.communicate" />         <intent>             <action android:name="android.media.browse.MediaBrowserService" />         </intent>@@ -142,6 +143,29 @@             <action android:name="android.intent.action.DIAL" />             <data android:scheme="tel" />         </intent>+        <!-- Third-party car apps: the launcher discovers CarAppService+             implementations per category (navigation, POI, IoT, weather) and+             hosts their templates generically. -->+        <intent>+            <action android:name="androidx.car.app.CarAppService" />+            <category android:name="androidx.car.app.category.NAVIGATION" />+        </intent>+        <intent>+            <action android:name="androidx.car.app.CarAppService" />+            <category android:name="androidx.car.app.category.POI" />+        </intent>+        <intent>+            <action android:name="androidx.car.app.CarAppService" />+            <category android:name="androidx.car.app.category.IOT" />+        </intent>+        <intent>+            <action android:name="androidx.car.app.CarAppService" />+            <category android:name="androidx.car.app.category.WEATHER" />+        </intent>+        <intent>+            <action android:name="androidx.car.app.CarAppService" />+            <category android:name="androidx.car.app.category.MESSAGING" />+        </intent>     </queries>      <application
auto/src/main/java/com/vayunmathur/auto/Navigation.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/Navigation.kt b/auto/src/main/java/com/vayunmathur/auto/Navigation.ktindex 2836b3542e..d82af7f86e 100644--- a/auto/src/main/java/com/vayunmathur/auto/Navigation.kt+++ b/auto/src/main/java/com/vayunmathur/auto/Navigation.kt@@ -5,6 +5,7 @@ import com.vayunmathur.auto.platform.AutoViewModel import com.vayunmathur.auto.platform.PairingViewModel import com.vayunmathur.auto.ui.AutoScreen import com.vayunmathur.auto.ui.PairingScreen+import com.vayunmathur.auto.ui.PinnedAppsScreen import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.rememberNavBackStack @@ -13,10 +14,17 @@ fun Navigation(viewModel: AutoViewModel, pairingViewModel: PairingViewModel) {     val backStack = rememberNavBackStack<Route>(Route.Home)     MainNavigation(backStack) {         entry<Route.Home> {-            AutoScreen(viewModel = viewModel, onPairing = { backStack.add(Route.Pairing) })+            AutoScreen(+                viewModel = viewModel,+                onPairing = { backStack.add(Route.Pairing) },+                onPinnedApps = { backStack.add(Route.PinnedApps) },+            )         }         entry<Route.Pairing> {             PairingScreen(viewModel = pairingViewModel, onNavigateBack = { backStack.pop() })         }+        entry<Route.PinnedApps> {+            PinnedAppsScreen(onNavigateBack = { backStack.pop() })+        }     } }
auto/src/main/java/com/vayunmathur/auto/Route.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/Route.kt b/auto/src/main/java/com/vayunmathur/auto/Route.ktindex c6fe372e4b..0f751d0df7 100644--- a/auto/src/main/java/com/vayunmathur/auto/Route.kt+++ b/auto/src/main/java/com/vayunmathur/auto/Route.kt@@ -16,4 +16,8 @@ sealed interface Route : NavKey {     /** USB + wireless bring-up, the winning transport, and the MAOS role. */     @Serializable     data object Pairing : Route++    /** The car dock pin picker: which car apps sit in the bottom bar. */+    @Serializable+    data object PinnedApps : Route }
auto/src/main/java/com/vayunmathur/auto/data/PinnedAppsPrefs.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/data/PinnedAppsPrefs.kt b/auto/src/main/java/com/vayunmathur/auto/data/PinnedAppsPrefs.ktnew file mode 100644index 0000000000..a84422f692--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/data/PinnedAppsPrefs.kt@@ -0,0 +1,63 @@+package com.vayunmathur.auto.data++import android.content.Context+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map++/**+ * Persists the car launcher's pinned dock: an ordered list of car-app+ * component ids (see `DiscoveredApp.id`), max 5.+ *+ * A single ordered delimited string, never a StringSet: sets lose the dock+ * order. Mirrors the `MessagingPrefs`/`MusicCapturePrefs` shape (device-level,+ * survives disconnects and restarts, fail-closed to empty). Stale ids (apps+ * no longer installed) are intersected out on load against the discovered set.+ */+object PinnedAppsPrefs {+    /** Max pinned apps in the car dock. Enforced on write. */+    const val MAX_PINNED = 5++    /** Ordered pinned ids; empty until the user pins something. */+    fun pinnedFlow(context: Context): Flow<List<String>> =+        DataStoreUtils.getInstance(context).stringFlow(KEY_PINNED).map { it.toIdList() }++    /** Synchronous snapshot for the car display's pin query. */+    fun pinnedNow(context: Context): List<String> =+        DataStoreUtils.getInstance(context).getString(KEY_PINNED)?.toIdList().orEmpty()++    /** Replaces the order wholesale, truncating to [MAX_PINNED]. */+    suspend fun setPinned(context: Context, ids: List<String>) {+        DataStoreUtils.getInstance(context).setString(KEY_PINNED, ids.take(MAX_PINNED).joinToString(SEPARATOR))+    }++    /** Pins [id] at the end; no-op when full or already pinned. Returns false when rejected. */+    suspend fun pin(context: Context, id: String): Boolean {+        val current = pinnedNow(context)+        if (id in current) return true+        if (current.size >= MAX_PINNED) return false+        setPinned(context, current + id)+        return true+    }++    /** Unpins [id]; no-op when absent. */+    suspend fun unpin(context: Context, id: String) {+        val current = pinnedNow(context)+        if (id !in current) return+        setPinned(context, current - id)+    }++    /** Moves [id] to [toIndex] within the pinned order; no-op when absent. */+    suspend fun move(context: Context, id: String, toIndex: Int) {+        val current = pinnedNow(context).toMutableList()+        if (!current.remove(id)) return+        current.add(toIndex.coerceIn(0, current.size), id)+        setPinned(context, current)+    }++    private fun String.toIdList(): List<String> =+        split(SEPARATOR).map { it.trim() }.filter { it.isNotEmpty() }.take(MAX_PINNED)++    private const val KEY_PINNED = "car_pinned_apps"+    private const val SEPARATOR = "\n"+}
auto/src/main/java/com/vayunmathur/auto/domain/PinnedAppsViewModel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/domain/PinnedAppsViewModel.kt b/auto/src/main/java/com/vayunmathur/auto/domain/PinnedAppsViewModel.ktnew file mode 100644index 0000000000..ef79c264ed--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/domain/PinnedAppsViewModel.kt@@ -0,0 +1,103 @@+package com.vayunmathur.auto.domain++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.auto.data.PinnedAppsPrefs+import com.vayunmathur.auto.platform.CarAppDiscovery+import com.vayunmathur.auto.platform.DiscoveredApp+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch++/** One row in the pin picker: the app plus its pinned rank (null = unpinned). */+data class PinnedAppRow(+    val app: DiscoveredApp,+    val rank: Int?,+)++/**+ * The phone pin picker state: every discovered car app plus the pinned order.+ *+ * Toggle pins/unpins (guarding the max-5 cap, reporting rejection so the UI+ * can snackbar); move reorders. All writes go through [PinnedAppsPrefs].+ */+class PinnedAppsViewModel(application: Application) : AndroidViewModel(application) {+    private val context = application.applicationContext++    private val _allApps = MutableStateFlow<List<DiscoveredApp>>(emptyList())++    /** Every discovered car app, in label order. */+    val allApps: StateFlow<List<DiscoveredApp>> = _allApps++    /** Ordered pinned ids, intersected with the discovered set. */+    val pinnedIds: StateFlow<List<String>> = PinnedAppsPrefs.pinnedFlow(context)+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), emptyList())++    /** Picker rows: pinned first in dock order, then the rest in label order. */+    val rows: StateFlow<List<PinnedAppRow>> = combine(_allApps, pinnedIds) { apps, pinned ->+        val rankById = pinned.withIndex().associate { (index, id) -> id to index }+        val pinnedRows = pinned.mapNotNull { id ->+            apps.firstOrNull { it.id == id }?.let { PinnedAppRow(it, rankById[id]) }+        }+        val unpinned = apps.filter { it.id !in rankById }.map { PinnedAppRow(it, null) }+        pinnedRows + unpinned+    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), emptyList())++    /** Emits ids the toggle rejected (dock full); the UI snackbars on these. */+    private val _rejected = MutableStateFlow<String?>(null)+    val rejected: StateFlow<String?> = _rejected++    init {+        refresh()+    }++    /** Re-runs discovery (package changes while the picker is open). */+    fun refresh() {+        viewModelScope.launch {+            _allApps.value = runCatching { CarAppDiscovery.queryAll(context) }.getOrDefault(emptyList())+        }+    }++    /** Pins or unpins [id]; reports rejection when the dock is full. */+    fun toggle(id: String) {+        viewModelScope.launch {+            val pinned = PinnedAppsPrefs.pinnedNow(context)+            if (id in pinned) {+                PinnedAppsPrefs.unpin(context, id)+            } else if (!PinnedAppsPrefs.pin(context, id)) {+                _rejected.value = id+            }+        }+    }++    /** Clears a delivered rejection. */+    fun consumeRejected() {+        _rejected.value = null+    }++    /** Moves [id] one step toward the front of the dock. */+    fun moveUp(id: String) {+        viewModelScope.launch {+            val pinned = PinnedAppsPrefs.pinnedNow(context)+            val index = pinned.indexOf(id)+            if (index > 0) PinnedAppsPrefs.move(context, id, index - 1)+        }+    }++    /** Moves [id] one step toward the back of the dock. */+    fun moveDown(id: String) {+        viewModelScope.launch {+            val pinned = PinnedAppsPrefs.pinnedNow(context)+            val index = pinned.indexOf(id)+            if (index >= 0) PinnedAppsPrefs.move(context, id, index + 1)+        }+    }++    private companion object {+        const val STOP_TIMEOUT_MS = 5_000L+    }+}
auto/src/main/java/com/vayunmathur/auto/platform/CarAppDiscovery.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarAppDiscovery.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarAppDiscovery.ktnew file mode 100644index 0000000000..674a24fe13--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarAppDiscovery.kt@@ -0,0 +1,141 @@+package com.vayunmathur.auto.platform++import android.content.ComponentName+import android.content.Context+import android.content.pm.PackageManager+import android.graphics.drawable.Drawable+import android.util.Log+import androidx.car.app.CarAppService++/**+ * One car-app-capable app: its service component, label, icon and the+ * categories it declared.+ */+data class DiscoveredApp(+    val component: ComponentName,+    val label: CharSequence,+    val icon: Drawable?,+    val categories: Set<String>,+) {+    /** Stable pin id: the flattened component string. */+    val id: String get() = component.flattenToString()+}++/**+ * Discovers third-party car apps through `PackageManager`, plus first-party+ * services by explicit component.+ *+ * Queries `CarAppService.SERVICE_INTERFACE` once per category the launcher+ * hosts (navigation, POI, IoT, weather): the manifest's `<queries>` block+ * keeps those lookups visible on Android 11+. Results merge by component so+ * an app declaring two categories appears once with both. First-party+ * services (music, communicate) publish categories the generic query does+ * not cover — `androidx.car.app.category.MEDIA` is not even a library+ * constant — so [queryAll] merges explicit components ahead of category+ * results, with real app icons resolved through `PackageManager`.+ */+object CarAppDiscovery {+    fun query(context: Context): List<DiscoveredApp> {+        val pm = context.packageManager+        val merged = linkedMapOf<ComponentName, MutableSet<String>>()+        for (category in HOSTED_CATEGORIES) {+            val intent = android.content.Intent(CarAppService.SERVICE_INTERFACE)+                .addCategory(category)+            val found = runCatching {+                pm.queryIntentServices(intent, PackageManager.GET_META_DATA)+            }.getOrElse {+                Log.w(TAG, "could not query car apps for $category", it)+                emptyList()+            }+            for (info in found) {+                val component = ComponentName(info.serviceInfo.packageName, info.serviceInfo.name)+                merged.getOrPut(component) { linkedSetOf() } += category+            }+        }+        return merged.mapNotNull { (component, categories) ->+            runCatching {+                val info = pm.getServiceInfo(component, 0)+                DiscoveredApp(+                    component = component,+                    label = info.loadLabel(pm),+                    icon = runCatching { info.loadIcon(pm) }.getOrNull(),+                    categories = categories,+                )+            }.getOrElse {+                Log.w(TAG, "could not load car app $component", it)+                null+            }+        }.sortedBy { it.label.toString().lowercase() }+    }++    /** Categories the launcher hosts templates for. */+    val HOSTED_CATEGORIES: List<String> = listOf(+        CarAppService.CATEGORY_NAVIGATION_APP,+        CarAppService.CATEGORY_POI_APP,+        CarAppService.CATEGORY_IOT_APP,+        CarAppService.CATEGORY_WEATHER_APP,+        CarAppService.CATEGORY_MESSAGING_APP,+        CarAppService.CATEGORY_CALLING_APP,+        CarAppService.CATEGORY_MEDIA_APP,+    )++    /**+     * Category query plus first-party services, by component id: what the+     * dock, the pin picker, and the host session all list. First-party+     * entries win on id collisions so their explicit category survives.+     */+    fun queryAll(context: Context): List<DiscoveredApp> {+        val byId = query(context).associateBy { it.id }.toMutableMap()+        for (party in firstParty(context)) {+            byId[party.id] = party+        }+        return byId.values.sortedBy { it.label.toString().lowercase() }+    }++    /**+     * First-party car services by explicit component, with labels and icons+     * resolved from the installed packages (missing packages resolve to+     * null and are skipped, so uninstalls never show dead tiles).+     */+    fun firstParty(context: Context): List<DiscoveredApp> {+        val pm = context.packageManager+        return FIRST_PARTY_COMPONENTS.mapNotNull { (packageName, className, label, categories) ->+            runCatching {+                val info = pm.getApplicationInfo(packageName, 0)+                DiscoveredApp(+                    component = ComponentName(packageName, className),+                    label = label,+                    icon = runCatching { pm.getApplicationIcon(info) }.getOrNull(),+                    categories = categories,+                )+            }.getOrElse {+                Log.w(TAG, "first-party car app not installed: $packageName", it)+                null+            }+        }+    }++    private data class FirstPartyComponent(+        val packageName: String,+        val className: String,+        val label: String,+        val categories: Set<String>,+    )++    private val FIRST_PARTY_COMPONENTS: List<FirstPartyComponent> = listOf(+        FirstPartyComponent(+            packageName = "com.vayunmathur.music",+            className = "com.vayunmathur.music.service.car.MusicCarAppService",+            label = "Music",+            categories = setOf("androidx.car.app.category.MEDIA"),+        ),+        FirstPartyComponent(+            packageName = "com.vayunmathur.communicate",+            className = "com.vayunmathur.communicate.service.car.CommunicateCarAppService",+            label = "Communicate",+            categories = setOf(CarAppService.CATEGORY_MESSAGING_APP),+        ),+    )++    private const val TAG = "MaAuto.CarDiscovery"+}
auto/src/main/java/com/vayunmathur/auto/platform/CarApps.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarApps.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarApps.ktindex 693936fe22..90a645c9e2 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/CarApps.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarApps.kt@@ -16,18 +16,38 @@ data class CarApp( /**  * Which apps the car launcher shows.  *- * The app-inventory pass (Task 10) found no third-party Android Auto targets on the phone,- * so the launcher resolves Modern Apps siblings plus the platform's own media surfaces:- * navigation goes to MA Maps, audio to MA Music's media browser service or any declared- * `MediaBrowserService`, and telephony to the system dialer. Whatever is not installed- * is skipped rather than shown dead, and an empty grid gets an explicit empty state.+ * Discovery-first: every `CarAppService` the phone reports (navigation, POI,+ * IoT, weather) becomes a tile whose tap opens the hosted template screen;+ * the legacy phone slots (Maps launch intent, media browser, dialer) remain+ * as open-on-phone fallbacks for apps with no car service. Whatever is not+ * installed is skipped rather than shown dead, and an empty grid gets an+ * explicit empty state.  */ object CarApps {-    fun query(context: Context): List<CarApp> {-        val pm = context.packageManager+    /**+     * Queries all car-capable apps, pinned first.+     *+     * [pinnedOrder] is flattened component strings (see [DiscoveredApp.id])+     * in dock order; entries that no longer resolve are filtered as stale.+     * Unpinned apps follow in label order, then the legacy phone slots.+     */+    fun query(context: Context, pinnedOrder: List<String> = emptyList()): List<CarApp> {+        val discovered = runCatching { CarAppDiscovery.query(context) }.getOrElse {+            Log.w(TAG, "car discovery failed; legacy slots only", it)+            emptyList()+        }+        val byId = discovered.associateBy { it.id }         val found = mutableListOf<CarApp>()+        for (id in pinnedOrder) {+            val app = byId[id] ?: continue+            found += app.toCarApp()+        }+        val pinnedIds = pinnedOrder.toSet()+        for (app in discovered) {+            if (app.id !in pinnedIds) found += app.toCarApp()+        }         for (slot in SLOTS) {-            runCatching { slot.resolve(context, pm) }+            runCatching { slot.resolve(context, context.packageManager) }                 .onSuccess { app -> if (app != null) found += app }                 .onFailure { Log.w(TAG, "could not resolve car slot ${slot.label}", it) }         }@@ -35,14 +55,9 @@ object CarApps {     }      /**-     * Resolves the assistant slot for the rail's assistant icon, or null when-     * the phone has no assistant to open.-     *-     * Skip-if-missing like every [SLOTS] entry: the rail keeps its 68dp-     * assistant container (gearhead `assistant_icon_container`) but the icon-     * itself stays GONE, so the launcher never shows what the phone cannot-     * open. `ACTION_ASSIST` first (the platform assistant entry point), then-     * the legacy voice-command intent as a fallback.+     * Resolves the assistant slot for the launcher's assistant affordance, or+     * null when the phone has no assistant to open. Skip-if-missing like every+     * [SLOTS] entry.      */     fun assistant(context: Context): CarApp? = runCatching {         val pm = context.packageManager@@ -60,6 +75,17 @@ object CarApps {         )     }.getOrNull() +    private fun DiscoveredApp.toCarApp(): CarApp {+        // Tapping a discovered tile opens its hosted template screen (Phase C+        // routes this through the launcher selection); the launch intent opens+        // the phone app as the pre-host fallback.+        val component = component+        val launch = Intent(Intent.ACTION_MAIN)+            .setClassName(component.packageName, component.className)+            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+        return CarApp(label = label, icon = icon, launch = launch)+    }+     private interface Slot {         val label: String         fun resolve(context: Context, pm: PackageManager): CarApp?
auto/src/main/java/com/vayunmathur/auto/platform/CarCallCard.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarCallCard.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarCallCard.ktdeleted file mode 100644index cfda873ba2..0000000000--- a/auto/src/main/java/com/vayunmathur/auto/platform/CarCallCard.kt+++ /dev/null@@ -1,198 +0,0 @@-package com.vayunmathur.auto.platform--import android.content.Context-import android.graphics.Color-import android.view.Gravity-import android.view.View-import android.widget.LinearLayout-import android.widget.TextView-import com.vayunmathur.auto.R-import com.vayunmathur.auto.platform.CarUiMetrics.BUTTON_DISABLED_ALPHA-import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_CARD_DAY-import com.vayunmathur.auto.platform.CarUiMetrics.COLOR_SUBTITLE-import com.vayunmathur.auto.platform.CarUiMetrics.MATCH-import com.vayunmathur.auto.platform.CarUiMetrics.WRAP--/**- * The projected call card (`UnCallView` parity): incoming vs active- * rows with the 44dp (`un_ar_icon_size`) action buttons, the end-call- * FAB focusable, and the `PHONE_FACET` content description. Held calls- * disable the row with the button-disabled alpha. GONE with no live- * call; the duration ticks every second like `postDelayed(l, 1000)`.- *- * Owns its views; the presentation drives state through [update] (null- * hides) and ticks duration through [tickDuration]. Actions route to the- * bound InCallService through the constructor callbacks. Views, not- * Compose (private display, no lifecycle owner).- */-internal class CarCallCardView(-    private val context: Context,-    private val onAnswer: () -> Unit,-    private val onEnd: () -> Unit,-    private val onHold: () -> Unit,-    private val onMute: () -> Unit,-) {-    private fun dp(value: Int): Int = context.carDp(value)--    private var callCardView: LinearLayout? = null-    private var callName: TextView? = null-    private var callState: TextView? = null-    private var callActions: LinearLayout? = null--    /**-     * Inner active-call snapshot: set by [update], read by [tickDuration],-     * so duration ticks against the card's own state.-     */-    private var innerActiveCall: ActiveCallInfo? = null--    /** Late-wired actions (service wires after `show()` starts the build). */-    var tapAnswer: () -> Unit = onAnswer-    var tapEnd: () -> Unit = onEnd-    var tapHold: () -> Unit = onHold-    var tapMute: () -> Unit = onMute--    /** The assembled card; add once above the nav/media split. */-    val view: LinearLayout = callCard()--    /** Clears view refs; call from `onStop`. */-    fun clear() {-        callCardView = null-        callName = null-        callState = null-        callActions = null-        innerActiveCall = null-    }--    /**-     * Pushes one active-call snapshot into the card. Main thread only;-     * null hides the card. Incoming shows answer/decline; active shows-     * end/mute/hold with the hold-disabled alpha; the duration ticks on-     * the 1Hz ticker while active.-     */-    fun update(info: ActiveCallInfo?) {-        innerActiveCall = info-        val card = callCardView ?: return-        if (info == null) {-            card.visibility = View.GONE-            return-        }-        card.visibility = View.VISIBLE-        val name = callName ?: return-        name.text = info.number ?: context.getString(R.string.car_call_unknown)-        val state = callState-        if (state != null) {-            state.text = if (info.isIncoming) {-                context.getString(R.string.car_call_incoming)-            } else {-                context.getString(R.string.car_call_active)-            }-        }-        val row = callActions ?: return-        row.removeAllViews()-        if (info.isIncoming) {-            row.addView(callActionButton(context.getString(R.string.car_call_answer)) { tapAnswer() })-            row.addView(callActionButton(context.getString(R.string.car_call_decline)) { tapEnd() })-        } else {-            val end = callActionButton(context.getString(R.string.car_call_end)) { tapEnd() }-            end.isFocusable = true-            row.addView(end)-            val mute = callActionButton(-                if (info.muted) context.getString(R.string.car_call_unmute)-                else context.getString(R.string.car_call_mute),-            ) { tapMute() }-            val hold = callActionButton(-                if (info.held) context.getString(R.string.car_call_resume)-                else context.getString(R.string.car_call_hold),-            ) { tapHold() }-            if (info.held) {-                // Held: row disabled with the button-disabled alpha.-                mute.isEnabled = false-                hold.isEnabled = false-                mute.alpha = BUTTON_DISABLED_ALPHA-                hold.alpha = BUTTON_DISABLED_ALPHA-            }-            row.addView(mute)-            row.addView(hold)-        }-    }--    /**-     * Ticks the active-call duration once per second. Main thread only;-     * called from the 1Hz ticker. Incoming (ringing) shows no duration;-     * active shows mm:ss since accept; held freezes on the held snapshot.-     */-    fun tickDuration() {-        val info = innerActiveCall ?: return-        val state = callState ?: return-        if (info.isIncoming || info.acceptedMs <= 0L) return-        val elapsed = ((System.currentTimeMillis() - info.acceptedMs) / 1000).coerceAtLeast(0)-        state.text = context.getString(-            R.string.car_call_duration,-            elapsed / 60,-            elapsed % 60,-        )-    }--    private fun callCard(): LinearLayout {-        return LinearLayout(context).apply {-            orientation = LinearLayout.VERTICAL-            gravity = Gravity.CENTER-            setBackgroundColor(Color.parseColor(COLOR_CARD_DAY))-            setPadding(dp(16), dp(16), dp(16), dp(16))-            visibility = View.GONE-            layoutParams = LinearLayout.LayoutParams(MATCH, WRAP).apply {-                topMargin = dp(8)-            }-            contentDescription = "phone"-            addView(-                TextView(context).apply {-                    textSize = 24f-                    setTextColor(Color.WHITE)-                    gravity = Gravity.CENTER-                    maxLines = 1-                    callName = this-                },-            )-            addView(-                TextView(context).apply {-                    textSize = 18f-                    setTextColor(Color.parseColor(COLOR_SUBTITLE))-                    gravity = Gravity.CENTER-                    callState = this-                },-            )-            addView(-                LinearLayout(context).apply {-                    orientation = LinearLayout.HORIZONTAL-                    gravity = Gravity.CENTER-                    layoutParams = LinearLayout.LayoutParams(MATCH, WRAP).apply {-                        topMargin = dp(12)-                    }-                    callActions = this-                },-            )-            callCardView = this-        }-    }--    /** One 44dp (`un_ar_icon_size`) call action button. */-    private fun callActionButton(label: String, onTap: () -> Unit): TextView {-        return TextView(context).apply {-            text = label-            setTextColor(Color.WHITE)-            textSize = 18f-            gravity = Gravity.CENTER-            background = context.carFocusRingBackground()-            isClickable = true-            isFocusable = true-            minWidth = dp(44)-            minHeight = dp(44)-            setPadding(dp(12), dp(8), dp(12), dp(8))-            layoutParams = LinearLayout.LayoutParams(WRAP, WRAP).apply {-                marginStart = dp(8)-                marginEnd = dp(8)-            }-            setOnClickListener { onTap() }-        }-    }-}
auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.ktindex 919b67aa7f..1a7c43936c 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplay.kt@@ -2,37 +2,20 @@ package com.vayunmathur.auto.platform  import android.app.Presentation import android.content.Context-import android.graphics.Color-import android.graphics.Outline-import android.graphics.SurfaceTexture+import android.content.res.Configuration import android.hardware.display.DisplayManager import android.hardware.display.VirtualDisplay-import android.os.Bundle import android.os.Handler import android.os.Looper import android.util.Log-import android.view.Gravity import android.view.KeyEvent import android.view.MotionEvent import android.view.Surface-import android.view.TextureView-import android.view.View-import android.view.ViewConfiguration-import android.view.ViewGroup-import android.view.ViewOutlineProvider-import android.widget.FrameLayout-import android.widget.GridLayout-import android.widget.ImageView-import android.widget.LinearLayout-import android.widget.ProgressBar-import android.widget.ScrollView-import android.widget.Space-import android.widget.TextView+import androidx.lifecycle.setViewTreeLifecycleOwner+import androidx.lifecycle.setViewTreeViewModelStoreOwner+import androidx.savedstate.setViewTreeSavedStateRegistryOwner import com.vayunmathur.auto.BuildConfig-import com.vayunmathur.auto.R import com.vayunmathur.auto.protocol.NavSnapshot-import java.text.DateFormat-import java.util.Date import java.util.concurrent.ExecutionException import java.util.concurrent.FutureTask @@ -46,8 +29,10 @@ import java.util.concurrent.FutureTask  * get pixels onto a head unit and prove the video path end to end — so the DHU  * loopback path never needs the flag.  *- * Views, not Compose: a `Presentation` on a private virtual display has no Compose- * lifecycle owner, and Views render into the encoder surface with no extra plumbing.+ * Compose, with its own lifecycle: the private virtual display has no activity+ * lifecycle, so the display owns a [CarDisplayLifecycle] stepped manually and+ * sets its three `ViewTree` owners on the decor view before content goes in.+ * The hierarchy inside is a single `ComposeView` (see [CarPresentation]).  */ class CarDisplay(     private val context: Context,@@ -64,6 +49,7 @@ class CarDisplay( ) {     private var virtualDisplay: VirtualDisplay? = null     private var presentation: CarPresentation? = null+    private var carLifecycle: CarDisplayLifecycle? = null     private val mainHandler = Handler(Looper.getMainLooper())      /**@@ -215,6 +201,7 @@ class CarDisplay(             initialDrivingRestricted = drivingRestricted,             initialNight = nightDark,             initialActiveCall = activeCall,+            initialHostNav = hostNavState,             initialPhoneStatusSource = phoneStatusSource,             onMediaTap = { onMediaTap?.invoke() },             onPreviousTap = { onPreviousTap?.invoke() },@@ -254,23 +241,22 @@ class CarDisplay(             this.width = width             this.height = height             this.densityDpi = densityDpi-            presentation?.dismiss()-            presentation = null-            virtualDisplay?.release()-            virtualDisplay = null+            tearDownPresentation()             show(surface)         }     }      /**      * Refreshes the car now-playing card. Safe from any thread: the snapshot is-     * cached for presentations created later, and the view update hops to main.+     * pushed into the shared state (cached for presentations created later),+     * and collection hops to main through the presentation lifecycle.      *      * The snapshot is always cached, even when the card hides: a pause still      * pushes `playing=false`, which is what clears a stale "Playing" label.      */     fun setNowPlaying(info: NowPlayingInfo) {         nowPlaying = info+        CarLauncherState.setNowPlaying(info)         mainHandler.post { presentation?.updateNowPlaying(info) }     } @@ -279,6 +265,7 @@ class CarDisplay(      * Safe from any thread; the card re-shows on the next visible snapshot.      */     fun hideNowPlaying() {+        CarLauncherState.hideNowPlaying()         mainHandler.post { presentation?.hideNowPlaying() }     } @@ -293,6 +280,7 @@ class CarDisplay(      */     fun setDrivingRestricted(restricted: Boolean) {         drivingRestricted = restricted+        CarLauncherState.setDrivingRestricted(restricted)         mainHandler.post { presentation?.setDrivingRestricted(restricted) }     } @@ -329,16 +317,27 @@ class CarDisplay(      */     fun setNight(dark: Boolean) {         nightDark = dark+        CarLauncherState.setNight(dark)         mapDarkApplier?.invoke(dark)         mainHandler.post { presentation?.setNight(dark) }     } +    /**+     * Forwards a night config change into the Compose tree. Called when the+     * night source changes underneath the virtual display; the presentation+     * re-reads uiMode into the flow so `DynamicTheme` follows.+     */+    fun onNightConfigChanged(newConfig: Configuration) {+        mainHandler.post { presentation?.onNightConfigChanged(newConfig) }+    }+     /**      * Pushes one active-call snapshot into the car card; null hides it.      * Safe from any thread; cached for presentations created later.      */     fun setActiveCall(info: ActiveCallInfo?) {         activeCall = info+        CarLauncherState.setActiveCall(info)         mainHandler.post { presentation?.updateCallCard(info) }     } @@ -350,6 +349,7 @@ class CarDisplay(      */     fun setHostNavState(state: HostNavState) {         hostNavState = state+        CarLauncherState.setHostNav(state)         mainHandler.post { presentation?.updateHostNav(state) }     } @@ -362,6 +362,7 @@ class CarDisplay(      * itself decides show vs GONE.      */     fun setNavSnapshot(snapshot: NavSnapshot) {+        CarLauncherState.setNavSnapshot(snapshot)         mainHandler.post { presentation?.updateNavSnapshot(snapshot) }     } @@ -379,6 +380,7 @@ class CarDisplay(      */     fun setMapSurfaceListener(listener: (Surface?, Int, Int) -> Unit) {         mapSurfaceForwarder = listener+        CarLauncherState.mapSurfaceListener = { surface, w, h -> listener(surface, w, h) }         mainHandler.post {             presentation?.mapSurfaceListener = { surface, w, h ->                 listener(surface, w, h)@@ -542,12 +544,44 @@ class CarDisplay(         val shown = presentation         presentation = null         if (shown != null) {-            if (isMainThread) shown.dismiss() else mainHandler.post { shown.dismiss() }+            if (isMainThread) {+                destroyPresentation(shown)+            } else {+                mainHandler.post { destroyPresentation(shown) }+            }+        } else {+            mainHandler.post { tearDownLifecycle() }         }         virtualDisplay?.release()         virtualDisplay = null     } +    /**+     * Tears the presentation down through the lifecycle: the Compose tree+     * moves to DESTROYED first (disposing composition), then the window+     * dismisses and the owners are cleared. Main thread only.+     */+    private fun destroyPresentation(shown: CarPresentation) {+        shown.dismiss()+        tearDownPresentation()+    }++    /** Tears the presentation + virtual display down. Main thread only. */+    private fun tearDownPresentation() {+        presentation?.dismiss()+        presentation = null+        tearDownLifecycle()+        virtualDisplay?.release()+        virtualDisplay = null+    }++    /** Moves the car lifecycle to DESTROYED and drops it. Main thread only. */+    private fun tearDownLifecycle() {+        val lifecycle = carLifecycle+        carLifecycle = null+        lifecycle?.moveToDestroyed()+    }+     /** Creates and shows the [CarPresentation] for [display] on the main thread. */     private fun showPresentation(         display: android.view.Display,@@ -555,6 +589,7 @@ class CarDisplay(         initialDrivingRestricted: Boolean,         initialNight: Boolean,         initialActiveCall: ActiveCallInfo?,+        initialHostNav: HostNavState?,         initialPhoneStatusSource: (() -> PhoneStatus?)?,         onMediaTap: () -> Unit,         onPreviousTap: () -> Unit,@@ -566,13 +601,13 @@ class CarDisplay(         onCardBounds: (Int, Int, Int, Int) -> Unit,     ): CarPresentation {         if (isMainThread) {-            return CarPresentation(-                context,+            return buildPresentation(                 display,                 initialNowPlaying,                 initialDrivingRestricted,                 initialNight,                 initialActiveCall,+                initialHostNav,                 initialPhoneStatusSource,                 onMediaTap,                 onPreviousTap,@@ -582,16 +617,16 @@ class CarDisplay(                 onHoldToggle,                 onMuteToggle,                 onCardBounds,-            ).also { it.show() }+            )         }         val show = FutureTask<CarPresentation> {-            CarPresentation(-                context,+            buildPresentation(                 display,                 initialNowPlaying,                 initialDrivingRestricted,                 initialNight,                 initialActiveCall,+                initialHostNav,                 initialPhoneStatusSource,                 onMediaTap,                 onPreviousTap,@@ -601,7 +636,7 @@ class CarDisplay(                 onHoldToggle,                 onMuteToggle,                 onCardBounds,-            ).also { it.show() }+            )         }         mainHandler.post(show)         try {@@ -618,6 +653,63 @@ class CarDisplay(         }     } +    /**+     * Builds the presentation: seeds the shared state from the cached+     * snapshots, wires the late-wired callbacks through the actions, creates+     * the car lifecycle, sets the three `ViewTree` owners on the decor view,+     * and steps to RESUMED. Main thread only.+     */+    private fun buildPresentation(+        display: android.view.Display,+        initialNowPlaying: NowPlayingInfo?,+        initialDrivingRestricted: Boolean,+        initialNight: Boolean,+        initialActiveCall: ActiveCallInfo?,+        initialHostNav: HostNavState?,+        initialPhoneStatusSource: (() -> PhoneStatus?)?,+        onMediaTap: () -> Unit,+        onPreviousTap: () -> Unit,+        onNextTap: () -> Unit,+        onAnswerCall: () -> Unit,+        onEndCall: () -> Unit,+        onHoldToggle: () -> Unit,+        onMuteToggle: () -> Unit,+        onCardBounds: (Int, Int, Int, Int) -> Unit,+    ): CarPresentation {+        initialNowPlaying?.let { CarLauncherState.setNowPlaying(it) }+        CarLauncherState.setDrivingRestricted(initialDrivingRestricted)+        CarLauncherState.setNight(initialNight)+        CarLauncherState.setActiveCall(initialActiveCall)+        initialHostNav?.let { CarLauncherState.setHostNav(it) }+        CarLauncherState.updateActions {+            it.copy(+                onMediaTap = onMediaTap,+                onPreviousTap = onPreviousTap,+                onNextTap = onNextTap,+                onAnswerCall = onAnswerCall,+                onEndCall = onEndCall,+                onHoldToggle = onHoldToggle,+                onMuteToggle = onMuteToggle,+            )+        }+        val lifecycle = CarDisplayLifecycle()+        carLifecycle = lifecycle+        return CarPresentation(+            context,+            display,+            onCardBounds,+        ).also { shown ->+            shown.setInnerPhoneStatusSource(initialPhoneStatusSource ?: { phoneStatusSource?.invoke() })+            shown.show()+            shown.window?.decorView?.let { decor ->+                decor.setViewTreeLifecycleOwner(lifecycle)+                decor.setViewTreeViewModelStoreOwner(lifecycle)+                decor.setViewTreeSavedStateRegistryOwner(lifecycle)+            }+            lifecycle.moveToResumed()+        }+    }+     /**      * Now-playing card bounds in display pixels, for ch8 tap routing.      * Compared in presentation root-view coordinates, which are 1:1 with
auto/src/main/java/com/vayunmathur/auto/platform/CarDisplayLifecycle.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplayLifecycle.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplayLifecycle.ktnew file mode 100644index 0000000000..f28e21cbca--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarDisplayLifecycle.kt@@ -0,0 +1,51 @@+package com.vayunmathur.auto.platform++import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleOwner+import androidx.lifecycle.LifecycleRegistry+import androidx.lifecycle.ViewModelStore+import androidx.lifecycle.ViewModelStoreOwner+import androidx.savedstate.SavedStateRegistry+import androidx.savedstate.SavedStateRegistryController+import androidx.savedstate.SavedStateRegistryOwner++/**+ * Lifecycle plumbing for the car [Presentation] on its private virtual display.+ *+ * A `Presentation` has no activity lifecycle, which is why the car surface was+ * Views-only. This owner supplies the three `ViewTree` owners Compose needs+ * (`LifecycleOwner`, `ViewModelStoreOwner`, `SavedStateRegistryOwner`) and is+ * driven manually: created alongside the `VirtualDisplay`, stepped to RESUMED+ * when the presentation shows, and torn down with it. The video/input path+ * (`VirtualDisplay` -> encoder surface, vsync drain, decorView touch dispatch)+ * is untouched; only the hierarchy inside becomes a `ComposeView`.+ */+class CarDisplayLifecycle :+    LifecycleOwner,+    ViewModelStoreOwner,+    SavedStateRegistryOwner {+    private val lifecycleRegistry = LifecycleRegistry(this)+    private val store = ViewModelStore()+    private val savedStateController = SavedStateRegistryController.create(this)++    override val lifecycle: Lifecycle get() = lifecycleRegistry+    override val viewModelStore: ViewModelStore get() = store+    override val savedStateRegistry: SavedStateRegistry get() = savedStateController.savedStateRegistry++    /** Steps CREATED -> STARTED -> RESUMED. Main thread only. */+    fun moveToResumed() {+        savedStateController.performAttach()+        savedStateController.performRestore(null)+        lifecycleRegistry.h

Diff truncated.