Modern Apps git

← Modern-Apps.git

auto: fix DHU sensor/input spam, host spinner hangs, hide refusing apps

Commit
a45dbf69e279c8ac395dedfe1f63ce70cee4bcf4
Author
Vayun Mathur <[email protected]>
When
2026-11-01 05:53 UTC (1 month ago)
Parents
f22ee8a
Found while testing projection on a Pixel 9 Pro XL against the Desktop
Head Unit (DHU 2.0).

Sensors
- The sensor channel subscribed to all 26 SensorType values. The DHU
  only advertises LOCATION, NIGHT_MODE and DRIVING_STATUS_DATA, so the
  rest came back STATUS_INVALID_SENSOR (-9), and types 23-26 are newer
  than the DHU's protocol: its lite parser drops the unknown enum and
  logs "Can't parse gal.SensorRequest ... missing required fields".
- SensorChannel now takes the advertised list from the discovery
  SensorSourceService entry and subscribes/unsubscribes only those.

Input
- onSessionFocusChanged re-sent the key-binding request on every focus
  verdict while input was allowed, so audio (0x13) and nav focus
  changes re-bound ch8 several times per session and on every tap.
- InputChannel.onInputFocusChanged now re-binds only when input focus
  returns after NO_INPUT_FOCUS, keeping the parked-input recovery the
  old code intended without the spam.

Car-app host (Google Messages loading forever)
- HostSession.hasService() read ServiceInfo.enabled, the manifest
  default. Google Messages ships its CarAppService enabled=false and
  enables it at runtime, so we treated it as missing, never bound it,
  and the launcher showed a spinner forever. It now uses
  resolveService(), which reflects the runtime enabled state.
- Every dead-end path (service off, bind failed, null binder, binding
  died, handshake failure/timeout, getManager/getTemplate failure or
  empty template) previously returned silently and left the spinner
  up. They now post a Message template naming the app, e.g.
  "Can't open Weather / Weather didn't respond."
- Once bound, Google Messages rejects the handshake: its HostValidator
  only allows Google's Android Auto ("CarApp.Val: Unrecognized host").
  That cannot be fixed host-side. roundTrip now distinguishes an
  explicit rejection from a timeout; a rejected onHandshakeCompleted
  marks the app refused (RefusedCarApps, persisted per app versionCode
  so an update gets a retry), hides it from the launcher for the
  session, and shows "<app> only works with car systems its developer
  has approved, like Android Auto." Discovery filters refused apps so
  they never appear in later sessions or the phone pin picker.
  Timeouts and crashes still show an error but never hide the app.
- CarAppHostSession publishes the discovery snapshot before binding so
  a fast refusal's hideApp cannot be overwritten.

Verified on device + DHU: one key binding at start (re-bind only after
NO_INPUT_FOCUS), 3 sensor subscribes all status=0 with no DHU parse
errors, Messages refused and hidden within ~20ms and skipped by
discovery on the next session, no fatal exceptions. :auto compile,
unit tests and lint pass.

Diff

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.ktindex c313c9f4df..e35d31020b 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/CarAppDiscovery.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarAppDiscovery.kt@@ -53,6 +53,10 @@ object CarAppDiscovery {             }         }         return merged.mapNotNull { (component, categories) ->+            if (RefusedCarApps.isRefused(context, component)) {+                Log.status(TAG, "hiding $component: it refused this host")+                return@mapNotNull null+            }             runCatching {                 val info = pm.getServiceInfo(component, 0)                 DiscoveredApp(
auto/src/main/java/com/vayunmathur/auto/platform/CarLauncherState.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/CarLauncherState.kt b/auto/src/main/java/com/vayunmathur/auto/platform/CarLauncherState.ktindex 49b06c1baa..75936145bb 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/CarLauncherState.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/CarLauncherState.kt@@ -6,6 +6,7 @@ import com.vayunmathur.library.carhost.HostTemplate import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.update  /**  * The car display's UI state, shared between the projection session and the@@ -156,6 +157,11 @@ object CarLauncherState {         _discovered.value = apps     } +    /** Drops one app from the grid and dock for the rest of the session. Thread-safe. */+    fun hideApp(id: String) {+        _discovered.update { apps -> apps.filterNot { it.id == id } }+    }+     /** Publishes one parsed template for [id]. Thread-safe. */     fun setTemplate(id: String, template: HostTemplate) {         _templates.value += id to template
auto/src/main/java/com/vayunmathur/auto/platform/HostManager.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/HostManager.kt b/auto/src/main/java/com/vayunmathur/auto/platform/HostManager.ktindex 02c1adb146..81ff465bc6 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/HostManager.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/HostManager.kt@@ -47,7 +47,16 @@ class HostManager(private val context: Context) {         val key = app.component         if (sessions.containsKey(key)) return         val category = app.categories.firstOrNull() ?: return-        val session = HostSession(context, key, category) { template ->+        val session = HostSession(+            context = context,+            component = key,+            category = category,+            label = app.label,+            onRefused = {+                RefusedCarApps.markRefused(context, key)+                CarLauncherState.hideApp(key.flattenToString())+            },+        ) { template ->             val id = key.flattenToString()             _templates.value += id to template             CarLauncherState.setTemplate(id, template)
auto/src/main/java/com/vayunmathur/auto/platform/HostSession.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/HostSession.kt b/auto/src/main/java/com/vayunmathur/auto/platform/HostSession.ktindex 760579e368..142dbcbab0 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/HostSession.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/HostSession.kt@@ -57,6 +57,10 @@ class HostSession(     context: Context,     private val component: ComponentName,     private val category: String,+    /** App name for car-facing error messages. */+    private val label: CharSequence,+    /** The app's host validator rejected us; called on the handshake thread. */+    private val onRefused: () -> Unit = {},     private val onTemplate: (HostTemplate) -> Unit = {}, ) {     private val appContext = context.applicationContext@@ -86,10 +90,13 @@ class HostSession(     /** The component this session hosts. */     fun componentName(): ComponentName = component -    /** Whether the car-app service resolves. */+    /**+     * Whether the car-app service resolves. Uses the runtime enabled state: apps such as+     * Google Messages ship the service `enabled=false` and turn it on via+     * `setComponentEnabledSetting`, which `ServiceInfo.enabled` never reflects.+     */     fun hasService(): Boolean = runCatching {-        val info = appContext.packageManager.getServiceInfo(component, 0)-        info.enabled+        appContext.packageManager.resolveService(Intent().setComponent(component), 0) != null     }.getOrDefault(false)      /** Binds the service; no-op when already bound or when the service is missing. */@@ -97,6 +104,7 @@ class HostSession(         if (bound) return         if (!hasService()) {             Log.status(TAG, "$component missing; stays unhosted")+            postError("$label has turned off its car support.")             return         }         val intent = Intent(CarAppService.SERVICE_INTERFACE).apply {@@ -109,6 +117,7 @@ class HostSession(                 Log.status(TAG, "$component connected; starting handshake")                 if (binder == null) {                     Log.status(TAG, "$component connected with null binder")+                    postError("$label didn't respond.")                     return                 }                 thread(name = "ma-auto-carhost", isDaemon = true) {@@ -126,6 +135,7 @@ class HostSession(              override fun onBindingDied(name: ComponentName?) {                 Log.status(TAG, "$component binding died")+                postError("$label stopped unexpectedly.")             }              override fun onNullBinding(name: ComponentName?) {@@ -140,6 +150,12 @@ class HostSession(         }.getOrDefault(false)         bound = ok         Log.status(TAG, "bindService returned $ok")+        if (!ok) postError("Couldn't connect to $label.")+    }++    /** Replaces the loading spinner with a terminal message; every dead-end bind path ends here. */+    private fun postError(message: String) {+        mainHandler.post { onTemplate(HostTemplate.Message(title = "Can't open $label", message = message)) }     }      /**@@ -252,13 +268,35 @@ class HostSession(     private fun runHandshake(app: ICarApp) {         carApp = app         Log.status(TAG, "starting car-app handshake for $component")-        val handshake = bundleOf(HandshakeInfo(appContext.packageName, HOST_API_LEVEL)) ?: return-        if (!roundTrip("onHandshakeCompleted") { cb -> app.onHandshakeCompleted(handshake, cb) }) return+        val handshake = bundleOf(HandshakeInfo(appContext.packageName, HOST_API_LEVEL)) ?: run {+            postError("$label couldn't start.")+            return+        }+        when (roundTrip("onHandshakeCompleted") { cb -> app.onHandshakeCompleted(handshake, cb) }) {+            CallResult.OK -> Unit+            // An explicit handshake rejection is the app's HostValidator: it only+            // accepts allowlisted hosts (Google Messages: Google's Android Auto).+            CallResult.REJECTED -> {+                Log.status(TAG, "$component refused this host")+                onRefused()+                postError("$label only works with car systems its developer has approved, like Android Auto.")+                return+            }+            CallResult.FAILED -> {+                postError("$label didn't respond.")+                return+            }+        }         val config = Configuration(appContext.resources.configuration)         val intent = Intent(Intent.ACTION_MAIN)-        if (!roundTrip("onAppCreate") { cb -> app.onAppCreate(carHostBinder, intent, config, cb) }) return-        if (!roundTrip("onAppStart") { cb -> app.onAppStart(cb) }) return-        if (!roundTrip("onAppResume") { cb -> app.onAppResume(cb) }) return+        val started =+            roundTrip("onAppCreate") { cb -> app.onAppCreate(carHostBinder, intent, config, cb) } == CallResult.OK &&+                roundTrip("onAppStart") { cb -> app.onAppStart(cb) } == CallResult.OK &&+                roundTrip("onAppResume") { cb -> app.onAppResume(cb) } == CallResult.OK+        if (!started) {+            postError("$label couldn't start.")+            return+        }         handshakeDone = true         mainHandler.post { onTemplate(HostTemplate.Pane(loading = true)) }         fetchTemplate()@@ -270,8 +308,10 @@ class HostSession(         Bundleable.create(value)     }.getOrNull() -    /** One blocking binder call with a 5s cap; false means the session is dead. */-    private fun roundTrip(name: String, call: (IOnDoneCallback) -> Unit): Boolean {+    private enum class CallResult { OK, REJECTED, FAILED }++    /** One blocking binder call with a 5s cap: REJECTED is the app saying no, FAILED is no answer. */+    private fun roundTrip(name: String, call: (IOnDoneCallback) -> Unit): CallResult {         Log.status(TAG, "$name: calling for $component")         val latch = CountDownLatch(1)         val failure = AtomicReference<Throwable?>(null)@@ -291,12 +331,16 @@ class HostSession(         }         runCatching { call(cb) }.onFailure {             Log.status(TAG, "$name binder call threw", it)-            return false+            return CallResult.FAILED         }         val done = runCatching { latch.await(CALL_TIMEOUT_MS, TimeUnit.MILLISECONDS) }.getOrDefault(false)         if (!done) Log.status(TAG, "$name timed out")         failure.get()?.let { Log.status(TAG, "$name rejected", it) }-        return done && failure.get() == null+        return when {+            failure.get() != null -> CallResult.REJECTED+            done -> CallResult.OK+            else -> CallResult.FAILED+        }     }      /** Pulls the current template and forwards it. Background thread. */@@ -318,10 +362,15 @@ class HostSession(             override fun getInterfaceVersion(): Int = IOnDoneCallback.VERSION         }         runCatching { app.getManager(CarContext.APP_SERVICE, managerCb) }-            .onFailure { Log.status(TAG, "getManager threw", it); return }+            .onFailure {+                Log.status(TAG, "getManager threw", it)+                postError("$label didn't respond.")+                return+            }         latch.await(CALL_TIMEOUT_MS, TimeUnit.MILLISECONDS)         val manager = managerRef.get() ?: run {             Log.status(TAG, "getManager returned no manager")+            postError("$label didn't respond.")             return         }         val templateRef = AtomicReference<Any?>(null)@@ -340,9 +389,17 @@ class HostSession(             override fun getInterfaceVersion(): Int = IOnDoneCallback.VERSION         }         runCatching { manager.getTemplate(templateCb) }-            .onFailure { Log.status(TAG, "getTemplate threw", it); return }+            .onFailure {+                Log.status(TAG, "getTemplate threw", it)+                postError("$label didn't respond.")+                return+            }         templateLatch.await(CALL_TIMEOUT_MS, TimeUnit.MILLISECONDS)-        val wrapper = templateRef.get() as? androidx.car.app.model.TemplateWrapper+        val wrapper = templateRef.get() as? androidx.car.app.model.TemplateWrapper ?: run {+            Log.status(TAG, "getTemplate returned no template for $component")+            postError("$label didn't respond.")+            return+        }         val parsed = HostTemplateParsers.parse(wrapper)         taskStack.record(parsed)         if (!taskStack.isAllowed(parsed)) {
auto/src/main/java/com/vayunmathur/auto/platform/InputChannel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/InputChannel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/InputChannel.ktindex 1308de4441..b19a2f59ef 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/InputChannel.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/InputChannel.kt@@ -71,12 +71,13 @@ class InputChannel(     @Volatile     private var bound = false +    /** Input focus was lost after binding; the next regain re-binds. */+    private var parked = false+     /**      * The grant arrived: echo the discovery-advertised keycodes back so the-     * head unit knows which keys we handle. Called once per channel open, and-     * again when video focus flaps back to PROJECTED with input (a head unit-     * that parked input may need the re-bind to resume sending reports).-     * Idempotent: re-sending the same echo is harmless.+     * head unit knows which keys we handle. Called once per channel open;+     * [onInputFocusChanged] re-sends it after a park.      */     fun requestBinding() {         val keycodes = service.inputSource.keycodesSupportedList@@ -87,6 +88,21 @@ class InputChannel(         onEvent(InputEvent.BindingRequested(keycodes.size))     } +    /**+     * Re-binds only when input returns after NO_INPUT_FOCUS: a head unit that parked+     * input may need the echo to resume reports. Audio/nav focus changes leave+     * [allowed] unchanged and must not re-send.+     */+    fun onInputFocusChanged(allowed: Boolean) {+        if (!bound) return+        if (!allowed) {+            parked = true+        } else if (parked) {+            parked = false+            requestBinding()+        }+    }+     /**      * Phone -> HU: one input-stream feedback event (`xjs`, 0x8004) from the      * discovery-advertised set. Sent after the phone consumes an input report
auto/src/main/java/com/vayunmathur/auto/platform/RefusedCarApps.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/RefusedCarApps.kt b/auto/src/main/java/com/vayunmathur/auto/platform/RefusedCarApps.ktnew file mode 100644index 0000000000..f0b09fa59b--- /dev/null+++ b/auto/src/main/java/com/vayunmathur/auto/platform/RefusedCarApps.kt@@ -0,0 +1,33 @@+package com.vayunmathur.auto.platform++import android.content.ComponentName+import android.content.Context++/**+ * Car apps that rejected our handshake, keyed to the app version that refused.+ *+ * A rejection is the app's host validator turning us away (Google Messages only+ * allows Google's Android Auto), so retrying every session is pointless. An app+ * update clears the verdict, since a new version may allow us.+ */+object RefusedCarApps {+    fun isRefused(context: Context, component: ComponentName): Boolean {+        val refusedAt = prefs(context).getLong(component.flattenToString(), NOT_REFUSED)+        return refusedAt != NOT_REFUSED && refusedAt == versionCode(context, component.packageName)+    }++    fun markRefused(context: Context, component: ComponentName) {+        val version = versionCode(context, component.packageName) ?: return+        prefs(context).edit().putLong(component.flattenToString(), version).apply()+    }++    private fun versionCode(context: Context, packageName: String): Long? = runCatching {+        context.packageManager.getPackageInfo(packageName, 0).longVersionCode+    }.getOrNull()++    private fun prefs(context: Context) =+        context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE)++    private const val FILE = "ma_auto_refused_car_apps"+    private const val NOT_REFUSED = -1L+}
auto/src/main/java/com/vayunmathur/auto/platform/SensorChannel.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/platform/SensorChannel.kt b/auto/src/main/java/com/vayunmathur/auto/platform/SensorChannel.ktindex 2a4faa812f..b4b05051bc 100644--- a/auto/src/main/java/com/vayunmathur/auto/platform/SensorChannel.kt+++ b/auto/src/main/java/com/vayunmathur/auto/platform/SensorChannel.kt@@ -28,7 +28,7 @@ fun interface NightSource { }  /**- * The sensor source channel: subscribes to the full 26-type set on the ch7+ * The sensor source channel: subscribes to the advertised sensor types on the ch7  * grant and folds the head unit's batches into a last-known snapshot.  *  * The channel id comes from discovery, not from [GalService]: the DHU 2.0@@ -63,6 +63,12 @@ class SensorChannel(     private val onValues: (SensorSnapshot) -> Unit = {},     /** Discovery-bound channel id (DHU 2.0: 1; gearhead rro: 7). */     val channelId: Int = GalService.SENSOR_SOURCE.id,+    /**+     * Types the head unit advertised in discovery. Subscribing to anything else earns+     * STATUS_INVALID_SENSOR, and enum values newer than the HU's protocol fail its+     * required-field parse outright (DHU 2.0 rejects types 23-26).+     */+    private val subscriptions: List<SensorType> = SensorCodec.STUB_SUBSCRIPTIONS, ) {     // (GalService import covers the default above.) @@ -73,7 +79,7 @@ class SensorChannel(     private var open = false      /**-     * Tracks the 26 subscribes against the 2 s `rvb` timeout: each subscribe+     * Tracks subscribes against the 2 s `rvb` timeout: each subscribe      * marks, each 0x8002 answer clears, and unanswered subscribes surface as      * synthesized errors on the next sweep (see [onMessage]).      */@@ -89,21 +95,16 @@ class SensorChannel(     private val pendingAnswers = ArrayDeque<SensorType>()      /**-     * The grant arrived: subscribe to the full 26-type set. Called once per+     * The grant arrived: subscribe to [subscriptions]. Called once per      * channel open. Night follows the phone until the first NIGHT_MODE batch      * -- the snapshot seeds from [night] now so the car UI has an answer      * before the head unit streams anything.-     *-     * `SensorCodec.STUB_SUBSCRIPTIONS` is the full set in dumper order despite-     * the kept name (see the protocol KDoc). Per-type 0x8004 errors are-     * observed and non-fatal, so a head unit that streams only a few types-     * still brings the channel up.      */     fun onChannelOpen() {         open = true         val seeded = _snapshot.value.copy(isNight = night.phoneNight())         _snapshot.value = seeded-        for (type in SensorCodec.STUB_SUBSCRIPTIONS) {+        for (type in subscriptions) {             val (requestType, payload) = SensorCodec.encodeSubscribe(type)             connection.send(channelId, requestType, payload)             requestTracker.markRequested(type, SystemClock.uptimeMillis())@@ -177,13 +178,13 @@ class SensorChannel(         onEvent(SensorEvent.BatchReceived(events.size))     } -    /** Unsubscribes the full set; the pump calls this on teardown before release. */+    /** Unsubscribes [subscriptions]; the pump calls this on teardown before release. */     fun release() {         if (!open) return         open = false         // Best-effort: the socket may already be going away in teardown, and         // an unsubscribe is courtesy, not protocol -- never fail the parting.-        for (type in SensorCodec.STUB_SUBSCRIPTIONS) {+        for (type in subscriptions) {             runCatching {                 val (requestType, payload) = SensorCodec.encodeUnsubscribe(type)                 connection.send(channelId, requestType, payload)
auto/src/main/java/com/vayunmathur/auto/service/CarAppHostSession.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/service/CarAppHostSession.kt b/auto/src/main/java/com/vayunmathur/auto/service/CarAppHostSession.ktindex 39fef9d9a3..6b17ab3b4c 100644--- a/auto/src/main/java/com/vayunmathur/auto/service/CarAppHostSession.kt+++ b/auto/src/main/java/com/vayunmathur/auto/service/CarAppHostSession.kt@@ -37,8 +37,9 @@ class CarAppHostSession(         val host = HostManager(context)         manager = host         val apps = discover()-        host.bindAll(apps)+        // Publish before binding: a refusing app's hideApp must land after this snapshot.         CarLauncherState.setDiscovered(apps)+        host.bindAll(apps)         CarLauncherState.updateActions {             it.copy(onAppHomeTap = { component -> resetApp(component) })         }
auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt b/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.ktindex 216f447461..e69c386195 100644--- a/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt+++ b/auto/src/main/java/com/vayunmathur/auto/service/ProjectionService.kt@@ -302,12 +302,7 @@ class ProjectionService : Service() {         AutoSessionState.onFocusChanged(connection.session.focus)         audioSys?.onFocusChanged()         audioMedia?.onFocusChanged()-        // Flapping back to input-allowed re-binds ch8: a head unit that-        // parked input on NO_INPUT_FOCUS may need the echo to resume-        // sending reports. requestBinding is idempotent.-        if (connection.session.focus.inputAllowed) {-            input?.requestBinding()-        }+        input?.onInputFocusChanged(connection.session.focus.inputAllowed)     }      /**
auto/src/main/java/com/vayunmathur/auto/service/ProjectionServiceChannels.kt
diff --git a/auto/src/main/java/com/vayunmathur/auto/service/ProjectionServiceChannels.kt b/auto/src/main/java/com/vayunmathur/auto/service/ProjectionServiceChannels.ktindex a8821c3263..6d05265641 100644--- a/auto/src/main/java/com/vayunmathur/auto/service/ProjectionServiceChannels.kt+++ b/auto/src/main/java/com/vayunmathur/auto/service/ProjectionServiceChannels.kt@@ -16,6 +16,7 @@ import com.vayunmathur.auto.protocol.AudioSinkRole import com.vayunmathur.auto.protocol.GalConnection import com.vayunmathur.auto.protocol.GalService import com.vayunmathur.auto.protocol.gal.Service as GalServiceProto+import com.vayunmathur.auto.protocol.gal.SensorType import com.vayunmathur.auto.service.ProjectionService.Companion.TAG import com.vayunmathur.auto.telephony.CarProjectionInCallService @@ -157,6 +158,7 @@ private fun ProjectionService.maybeCreateSensors(next: GalServiceProto, connecti         night = NightSource { isNightNow() },         onEvent = AutoSessionState::onSensorEvent,         channelId = next.id,+        subscriptions = next.sensorSource.sensorsList.mapNotNull { SensorType.forNumber(it.type) },     ) }