<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rohith Gaddam on Medium]]></title>
        <description><![CDATA[Stories by Rohith Gaddam on Medium]]></description>
        <link>https://medium.com/@rohithgd90?source=rss-3e5dc36b2b8f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dxUjBG9S9G_qTl__egOvEg@2x.jpeg</url>
            <title>Stories by Rohith Gaddam on Medium</title>
            <link>https://medium.com/@rohithgd90?source=rss-3e5dc36b2b8f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:50:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rohithgd90/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The HAL That Ran Fine by Hand]]></title>
            <link>https://proandroiddev.com/the-hal-that-ran-fine-by-hand-a85779adce90?source=rss-3e5dc36b2b8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a85779adce90</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[automotive]]></category>
            <dc:creator><![CDATA[Rohith Gaddam]]></dc:creator>
            <pubDate>Sun, 22 Nov 2026 15:43:56 GMT</pubDate>
            <atom:updated>2026-11-22T15:43:56.161Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why a Vehicle HAL that eventually ran cleanly from a root shell still kept an Android Automotive board in a restart loop, and what a real boot checks that a root shell never does.</em></p><p><em>Android Automotive System Internals — Part 4: init, SELinux &amp; the Vendor HAL Boot Path</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPyqUW_aXTSmf_9j7h7w_g.png" /></figure><p><a href="https://proandroiddev.com/the-speedometer-lied-debugging-real-time-ipc-in-android-automotive-0323df7d6234">The speedometer was fixed.</a></p><p><a href="https://proandroiddev.com/the-camera-that-launched-too-late-51717ac85c0d">The camera bug was fixed.</a></p><p><a href="https://proandroiddev.com/the-window-manager-lied-politely-f1789ae0dc34">The window manager was fixed.</a></p><p>A new vendor Vehicle HAL goes onto an AAOS 16 target. Same interface, IVehicle/default. Different backend: vehicle signals arrive over SOME/IP.</p><p>The board comes up. SystemUI appears.</p><p>The launcher never does.</p><p>Then the framework goes down and starts again. Roughly every 90 to 110 seconds.</p><p>No crash dialog. No adb, because the framework never stays up long enough for adbd to answer.</p><p>Eventually the service runs fine by hand from a root shell. The board still loops.</p><p>That was my bring-up. Three causes on the version that finally booted. Two of them lived in the build and the policy. Only one was in my C++.</p><h3>The Board Never Rebooted</h3><p>During the loop, the only way in was a serial console. I wired UART to the header pins and captured up to five minutes of a looping boot.</p><p>What the capture showed:</p><pre>What the capture showed                     How often<br>Booting Linux                               once<br>init sending SIGKILL to zygote              every cycle<br>sysrq: Show backtrace of all active CPUs    every cycle, right before the kill<br>carwatchdogd asking for IVehicle/default    every ~6 s, never answered</pre><p>Every line accurate. None of them named the problem.</p><p>The kernel booted exactly once. This was a framework restart loop: the platform waited for a Vehicle HAL that never registered, the framework went down, zygote restarted, and the wait began again.</p><p>I checked the other CPUs’ backtraces at one of those dumps. All idle. Nothing was spinning at the kernel level. Something was simply missing.</p><h3>Four Fixes That Changed Nothing</h3><p>First, I tried four fixes, each one through a full rebuild, reflash and reboot:</p><ol><li>Startup gave up if a connection wasn’t up yet at that point in boot. I stopped gating registration on it.</li><li>The middleware had no configuration file on the device. I shipped one.</li><li>My HAL exposed one property. Suspecting CarService needed the baseline set that FakeVehicleHardware ships, I composed with it instead of replacing it.</li><li>My service hung waiting on /dev/vndbinder. Pinning the binder driver at startup removed the hang. Why it happened in my service is still an open question.</li></ol><p>After fix 3 I compared the flashed partition byte for byte against the built image, past the ext4 superblock, to be sure the fix was really on the card. It was.</p><p>Same loop, every time.</p><p>My notes from those attempts had one more line. The hand-run tests, they said, ran “under a different SELinux domain” than the one init uses, so they could rule hypotheses out but could not reproduce the boot. I wrote that down as a limitation of the test.</p><p>It was part of the answer.</p><p>Then I rewrote the service as a single process, which changed its binary name. The loop came with it. Everything below happened on that version.</p><h3>The Harness That Gave Me adb Back</h3><p>The method that worked was a harness build:</p><ul><li>The default VHAL stays primary, so the board boots and adb works.</li><li>My binary is installed in /vendor/bin/hw/, and its .rc service is declared but disabled.</li></ul><p>Now I could run my service on a live system, from the image, with its output in front of me.</p><h4>Root cause 1: the plugins were never on the image</h4><p>Run by hand, it died at once with exit code 1:</p><pre>Configuration module could not be loaded!</pre><p>vsomeip loads its configuration and service-discovery modules at runtime with dlopen: libvsomeip3-cfg.so and libvsomeip3-sd.so. They are not NEEDED entries. The build-time linker never sees them, and neither does Soong.</p><p>So linking libvsomeip3 installed the core library and nothing else. The plugins never reached /vendor/lib64.</p><p>The fix is to name them:</p><pre>required: [ &quot;someip_vhal.vsomeip.json&quot;, &quot;libvsomeip3-cfg&quot;, &quot;libvsomeip3-sd&quot;, ... ]</pre><h4>Root cause 2: it ran as root, and init still said no</h4><p>With the plugins installed, the by-hand run worked. As the primary VHAL, the board still looped.</p><p>So I started it the way init does:</p><pre>adb root<br>adb shell start vendor.vehicle-hal-someip</pre><p>and init answered (trimmed, path shortened):</p><pre>init: [...] Could not ctl.start for &#39;vendor.vehicle-hal-someip&#39; [...]:<br>File .../@V4-someip-service(labeled &quot;u:object_r:vendor_file:s0&quot;) has incorrect label or no domain transition from<br>u:r:init:s0 to another SELinux domain defined. [...] Note: this error shows up even<br>in permissive mode in order to make auditing denials possible.</pre><p>This is a domain calculation, not an access denial, so the enforcement mode doesn’t change it. init computes the domain the new process will run in, and if the answer is init’s own domain, it won’t start the service.</p><h4>Root cause 3: my health check was tied to the network</h4><p>Once init could start the service, one restart remained: the launcher.</p><p>This one was in my code. My hardware layer’s checkHealth() returned INTERNAL_ERROR whenever the SOME/IP side wasn&#39;t up yet: peer down, network not ready, discovery still running.</p><p>DefaultVehicleHal sends carwatchdog its VHAL_HEARTBEAT only when checkHealth() returns OK. carwatchdog expects that heartbeat every 3 seconds by default. No heartbeat, and carwatchdog has the VHAL killed (the kill itself runs in system_server, through CarServiceHelperService). init respawns it, and CarService and the launcher churn with it.</p><p>The fix was to delegate checkHealth() to FakeVehicleHardware, which returns OK, the same as the stock service. A disconnected peer means SOME/IP values stop updating. The HAL itself is still alive.</p><h3>The Label That Decides the Domain</h3><p>AOSP’s stock system/sepolicy/vendor/file_contexts has one entry for AIDL Vehicle HAL binaries:</p><pre>/(vendor|system/vendor)/bin/hw/android\.hardware\.automotive\.vehicle@V[0-9]+-(default|emulator)-service  u:object_r:hal_vehicle_default_exec:s0</pre><p>@V4-default-service matches. @V4-emulator-service matches. @V4-someip-service falls back to the generic vendor_file.</p><p>Before:</p><pre>init  (u:r:init:s0)<br> └── exec @V4-someip-service<br>       file label:  vendor_file<br>       transition:  none defined<br>       result:      would run as u:r:init:s0  -&gt;  refused</pre><p>After one file_contexts line:</p><pre>init  (u:r:init:s0)<br> └── exec @V4-someip-service<br>       file label:  hal_vehicle_default_exec<br>       transition:  init_daemon_domain(hal_vehicle_default)<br>       result:      runs as u:r:hal_vehicle_default:s0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YMYoKqlDlE4kfY04rcHcbA.png" /></figure><h3>Why Both Hid</h3><p><strong>The by-hand run used a different door.</strong> A root shell executes the binary in the shell’s own domain. No transition is requested, so nothing is refused. init asks a question my shell never asks.</p><p><strong>Nothing in the toolchain knows about a plugin.</strong> The build succeeded, the binary linked, and every NEEDED library made it onto the image. Neither the linker nor Soong ever sees a library that only dlopen asks for. The first thing to notice it missing is the process itself, at runtime, on the device, however it is launched. That one, the root shell did catch.</p><h3>Inside init: Where the Decision Happens</h3><p>The refusal comes from system/core/init/service.cpp. Four steps.</p><p><strong>Step 1.</strong> start sends init a control message. init finds the service by name and calls Service::Start(), which checks that the executable exists.</p><p><strong>Step 2.</strong> If the .rc sets a seclabel, init uses it. Otherwise it calls ComputeContextFromExecutable() with the binary&#39;s path.</p><p><strong>Step 3.</strong> That function reads init’s own context (getcon) and the file&#39;s label (getfilecon), then asks the policy which domain a process created from that file would get (security_compute_create).</p><p><strong>Step 4.</strong> If the answer equals init’s own context, the function returns the error above. Start() passes it back. There is no fork, no exec, and no log line from your process. IVehicle/default never registers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9568iF5vC1HO37JQ0JzUiQ.png" /></figure><pre>if (rc == 0 &amp;&amp; computed_context == mycon.get()) {<br>    return Error() &lt;&lt; &quot;File &quot; &lt;&lt; service_path &lt;&lt; &quot;(labeled \&quot;&quot; &lt;&lt; filecon.get()<br>                   &lt;&lt; &quot;\&quot;) has incorrect label or no domain transition from &quot; ...<br>}</pre><h3>The Neverallow I Got Wrong</h3><p>A SOME/IP stack needs UDP sockets, netlink, and its own lock and socket files.</p><p>The obvious move is to grant those to hal_vehicle_default. That fails the policy build. system/sepolicy/private/hal_neverallows.te bars HAL server domains from network sockets.</p><p>My first note concluded that a SOME/IP VHAL needed a custom domain with its own neverallow exception.</p><p>That note was wrong. The same file carves out an attribute, with this comment:</p><blockquote>HALs for automotive devices have an exemption from this rule because in a car it is common to have external modules and HALs need to communicate to those modules using network. Using this exemption for non-automotive builds will result in CTS failure.</blockquote><p>Google’s Cuttlefish automotive target applies it to this exact domain with these two lines:</p><pre>typeattribute hal_vehicle_default hal_automotive_socket_exemption;<br>net_domain(hal_vehicle_default)</pre><p>I had drafted hand-written allow rules first. They were broader than that macro and still missed things. I replaced them with the two lines, plus one dedicated file type for vsomeip’s runtime directory. Its routing-manager lock and local endpoint sockets are load-bearing: without them SOME/IP never starts.</p><p>The board boots enforcing. The VHAL runs in u:r:hal_vehicle_default:s0 with zero hal_vehicle_default denials.</p><p>One question stays open. The exemption is a blanket attribute. Whether a SOME/IP VHAL should get it, or a narrower domain of its own, is a design decision in its own right.</p><h3>Why Any Renamed HAL Is Exposed</h3><p>The stock AIDL entry labels Google’s two reference names, at any interface version. Give your Vehicle HAL any other name and it gets vendor_file until you label it.</p><p>The same goes for anything a vendor service loads with dlopen. If the build graph can&#39;t see it, the image won&#39;t carry it.</p><p>Both failures look the same from outside: a framework restart loop with nothing from your process in any log.</p><h3>What the Working Image Carries</h3><p><strong>1. The module’s </strong><strong>Android.bp: install what you </strong><strong>dlopen.</strong></p><pre>required: [ &quot;someip_vhal.vsomeip.json&quot;, &quot;libvsomeip3-cfg&quot;, &quot;libvsomeip3-sd&quot;, ... ]</pre><p><strong>2. </strong><strong>sepolicy/file_contexts: give the binary a domain.</strong></p><pre>/vendor/bin/hw/android\.hardware\.automotive\.vehicle@V4-someip-service  u:object_r:hal_vehicle_default_exec:s0</pre><p><strong>3. The module’s </strong><strong>.te: let the HAL talk to the network.</strong></p><pre>typeattribute hal_vehicle_default hal_automotive_socket_exemption;<br>net_domain(hal_vehicle_default)</pre><p><strong>4. </strong><strong>BoardConfig.mk: make the board read that policy.</strong></p><pre>BOARD_SEPOLICY_DIRS += device/&lt;vendor&gt;/&lt;board&gt;/someip_vhal/sepolicy</pre><p>And in the hardware layer, keep checkHealth() independent of the network backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0OKaD5xHPAtF6dUsXNYt4w.png" /></figure><h3>The Diagnostic Workflow</h3><p><em>Bench: the logs, fixes and command outputs shown in this article were captured and verified on a Raspberry Pi 5 running AAOS 16.</em></p><p><strong>Check the label on your binary:</strong></p><pre>adb shell ls -Z /vendor/bin/hw/ | grep -i vehicle</pre><p>On the working image, a label init can transition from:</p><pre>u:object_r:hal_vehicle_default_exec:s0            android.hardware.automotive.vehicle@V4-someip-service</pre><p>Before the fix, that first field was u:object_r:vendor_file:s0, the label init&#39;s error reported. Unless its .rc sets a seclabel, a binary carrying it will not start from init.</p><p><strong>Start it the way init does.</strong> Use start; a shell launch skips the check you are testing. init writes to the kernel log, so read dmesg:</p><pre>adb root<br>adb shell start vendor.vehicle-hal-someip<br>adb shell dmesg | grep &quot;ctl.start&quot;</pre><p>Broken: the no domain transition line above. Working: no error, and the process shows up in its own domain:</p><pre>adb shell ps -AZ | grep -i vehicle</pre><pre>u:r:hal_can_socketcan:s0       vehicle_network 717    1   10908868   5952 binder_ioctl_write_read 0 S android.hardware.automotive.can-service<br>u:r:hal_vehicle_default:s0     vehicle_network 12997  1   11268304  21112 binder_ioctl_write_read 0 S android.hardware.automotive.vehicle@V4-someip-service</pre><p>The second line is the one that matters: the VHAL in its own domain, running as vehicle_network, parent PID 1.</p><p><strong>Check that the plugins made it onto the image:</strong></p><pre>adb shell ls /vendor/lib64 | grep vsomeip</pre><p>You want libvsomeip3-cfg.so and libvsomeip3-sd.so next to libvsomeip3.so. If only the core library is there, the service will exit at init().</p><p><strong>Read custom properties through CarService.</strong> If your hardware layer composes FakeVehicleHardware and delegates dump() to it, then dumpsys android.hardware.automotive.vehicle.IVehicle/default --get &lt;id&gt; answers No property &lt;id&gt; for every property you added. Your property is fine. Ask the binder path instead:</p><pre>adb shell cmd car_service list-vhal-props<br>adb shell cmd car_service get-property-value &lt;id&gt;</pre><h3>The Systemic Mental Model</h3><p><strong>A binary that runs is not a service that starts.</strong></p><p>A root shell is the loading dock. You walk in with the binary and it runs. If a plugin is missing, the process fails there too, because that failure lives inside the process. What the loading dock never does is check your badge. Only init asks for a domain. And only a booted platform has carwatchdog checking, every few seconds, that you are still alive.</p><p>Part 1 traced stale speed data to the IPC return path. Part 2 traced a late camera to process cold start. Part 3 traced a misplaced app to a launch request with half an address. Here, two of the three causes lived outside my C++, in the build and the policy, and one of them only shows up when init does the launching.</p><h3>What to Check on Your Build Today</h3><p>If you ship your own native vendor service on AAOS, run this:</p><pre>adb shell ls -Z /vendor/bin/hw/</pre><p>Any binary of yours labeled vendor_file, with no seclabel in its .rc, will not start from init, however well it runs from your shell.</p><p>Fix it before a bring-up board finds it for you, ninety seconds at a time.</p><p><em>Note: This article covers native vendor services started by init on AAOS, where Android runs on the vehicle hardware. It does not apply to Android Auto phone projection. The SOME/IP integration design itself is out of scope here.</em></p><h3>Key AOSP References</h3><ul><li><a href="https://cs.android.com/android/platform/superproject/main/+/main:system/core/init/service.cpp">system/core/init/service.cpp</a>: Service::Start(), ComputeContextFromExecutable()</li><li><a href="https://cs.android.com/android/platform/superproject/main/+/main:system/sepolicy/vendor/file_contexts">system/sepolicy/vendor/file_contexts</a>: stock Vehicle HAL executable labels</li><li><a href="https://cs.android.com/android/platform/superproject/main/+/main:system/sepolicy/vendor/hal_vehicle_default.te">system/sepolicy/vendor/hal_vehicle_default.te</a>: init_daemon_domain(hal_vehicle_default)</li><li><a href="https://cs.android.com/android/platform/superproject/main/+/main:system/sepolicy/private/hal_neverallows.te">system/sepolicy/private/hal_neverallows.te</a>: HAL socket neverallows and hal_automotive_socket_exemption</li><li><a href="https://cs.android.com/android/platform/superproject/main/+/main:device/google/cuttlefish/shared/auto/sepolicy/vendor/hal_vehicle_default.te">device/google/cuttlefish/shared/auto/sepolicy/vendor/hal_vehicle_default.te</a>: where the automotive reference applies the exemption</li><li><a href="https://cs.android.com/android/platform/superproject/main/+/main:hardware/interfaces/automotive/vehicle/aidl/impl/current/vhal/src/DefaultVehicleHal.cpp">hardware/interfaces/automotive/vehicle/aidl/impl/current/vhal/src/DefaultVehicleHal.cpp</a>: checkHealth() and the VHAL_HEARTBEAT</li><li><a href="https://cs.android.com/android/platform/superproject/main/+/main:hardware/interfaces/automotive/vehicle/aidl/impl/current/vhal/vhal-default-service.rc">hardware/interfaces/automotive/vehicle/aidl/impl/current/vhal/vhal-default-service.rc</a>: the stock service stanza (class early_hal, user vehicle_network)</li><li><a href="https://cs.android.com/android/platform/superproject/main/+/main:packages/services/Car/cpp/watchdog/server/src/WatchdogProcessService.cpp">packages/services/Car/cpp/watchdog/server/src/WatchdogProcessService.cpp</a>: carwatchdogd’s VHAL connection and heartbeat checks</li><li><a href="https://source.android.com/docs/security/features/selinux/device-policy#label_new_services_and_address_denials">Android SELinux: label new services</a>: the page init’s error message points to</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a85779adce90" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/the-hal-that-ran-fine-by-hand-a85779adce90">The HAL That Ran Fine by Hand</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Window Manager Lied Politely]]></title>
            <link>https://proandroiddev.com/the-window-manager-lied-politely-f1789ae0dc34?source=rss-3e5dc36b2b8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1789ae0dc34</guid>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[automotive]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Rohith Gaddam]]></dc:creator>
            <pubDate>Mon, 27 Apr 2026 05:58:06 GMT</pubDate>
            <atom:updated>2026-04-27T05:58:06.443Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How START_SUCCESS quietly sent my activity to the wrong pane — and why setLaunchDisplayId() is only half the address.</em></p><p><em>Android Automotive System Internals — Part 3: WindowManager &amp; Multi-Display Orchestration</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBJLHFJEJwh8A-pHq41Qog.png" /></figure><p><a href="https://proandroiddev.com/the-camera-that-launched-too-late-51717ac85c0d">The camera bug was fixed</a>.</p><p><a href="https://proandroiddev.com/the-speedometer-lied-debugging-real-time-ipc-in-android-automotive-0323df7d6234">The speedometer was fixed</a>.</p><p>We shipped the wide-format center console — two panes, one display, navigation on the left, media on the right.</p><p>On first boot, I drove into the parking lot, shifted into park, and tapped the home screen launcher.</p><p>The navigation app appeared on the right.</p><p>The media app disappeared behind it.</p><p>The left pane sat empty.</p><p>No crash. No exception. No stack trace. START_SUCCESS in logcat.</p><p>Three days to understand why.</p><h3>What Success Looks Like When You’re Wrong</h3><p>Here is what the logs showed the moment the navigation activity launched:</p><pre>ActivityTaskManager: START u0 {cmp=com.oem.navigation/.MapActivity} from uid 1000<br>ActivityTaskManager: Displayed com.oem.navigation/.MapActivity: +312ms<br>WindowManager: addWindow: Window{a1b2c3d u0 com.oem.navigation/...MapActivity}</pre><p>Every line accurate. Every line true.</p><p>The activity started. It rendered in 312ms. A window was registered. The framework fulfilled its contract completely.</p><p>It just placed the activity in the wrong zone.</p><p>That dissonance — <em>everything succeeded, nothing worked</em> — is what makes this class of bug expensive at an organizational level. You spend the first day convinced something is broken. You spend the second day reading correct log lines and refusing to believe them. You spend the third day realizing the framework was never told where the activity should actually go.</p><p>It knew the display. It had no idea about the pane.</p><h3>The Hidden Layer Android 12 Inserted</h3><p>Before Android 12, the window hierarchy on a single display was flat:</p><pre>RootWindowContainer<br>  └── DisplayContent  (display ID 0)<br>        └── ActivityStack / Task<br>              └── ActivityRecord</pre><p>setLaunchDisplayId(0) was sufficient. One display, one stack, one landing spot. Deterministic on every OEM build.</p><p>Android 12 inserted a new layer between DisplayContent and Task — TaskDisplayArea (TDA):</p><pre>RootWindowContainer<br>  └── DisplayContent  (display ID 0)<br>        └── TaskDisplayArea  ← NEW in Android 12<br>              └── Task<br>                    └── ActivityRecord</pre><p>On a phone there is typically one TDA per display, so nothing visibly changed. On an AAOS multi-pane build, the OEM configures multiple TDAs — one per pane. Left pane: feature ID 1. Right pane: feature ID 2. The layout is wired at boot via DisplayAreaPolicy.</p><p>When you call setLaunchDisplayId(0), you tell the framework which display to use. You say nothing about which pane. The framework calls getDefaultTaskDisplayArea(), gets whichever pane the OEM configured as the default, and places the activity there.</p><p>START_SUCCESS. Wrong pane. No error logged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rj7sS5ZxpevLnS6kF9K8GQ.png" /></figure><h3>Why the Bug Hid for Two Sprints</h3><p>The launcher was written with standard AOSP practice:</p><pre>ActivityOptions options = ActivityOptions.makeBasic();<br>options.setLaunchDisplayId(0);<br>context.startActivity(navigationIntent, options.toBundle());</pre><p>Correct by AOSP documentation. And it worked — on the emulator (one TDA per display) and on single-pane reference hardware. The failure was hardware-specific to the multi-pane build.</p><p>Two things made it invisible.</p><p><strong>Validation environment discrepancy.</strong> Automated integration tests checked whether the activity reached RESUMED. It did. START_SUCCESS returned. The test framework had no spatial awareness — it never verified which physical pane held the surface.</p><p><strong>Identical log output.</strong> START_SUCCESS carries no pane information. The only way to see where an activity actually landed is:</p><pre>adb shell dumpsys activity activities | grep -A 5 &quot;MapActivity&quot;</pre><p>I ran that on day three looking for something else entirely. The featureId in the output told me everything.</p><h3>Inside ActivityStarter: Where the Decision Happens</h3><p>The resolution happens in ActivityStarter.startActivityInner(). Four steps.</p><p><strong>Step 1.</strong> ActivityOptions.toBundle() serialises the launch request. Two relevant fields: KEY_LAUNCH_TASK_DISPLAY_AREA_TOKEN holding a WindowContainerToken, and KEY_LAUNCH_TASK_DISPLAY_AREA_FEATURE_ID holding an integer feature ID. If the caller only used setLaunchDisplayId(), both are absent.</p><p><strong>Step 2.</strong> setLaunchParams() copies the display ID. Null token stays null.</p><p><strong>Step 3.</strong> LaunchParamsController.calculate() iterates registered LaunchParamsModifier implementations. OEMs can inject routing policy here — but most don&#39;t, and your launcher can&#39;t rely on it.</p><p><strong>Step 4 — the fork.</strong> If mPreferredTaskDisplayArea is populated: resolveToTaskDisplayArea(token) — explicit, your pane. If null: getDefaultTaskDisplayArea() — OEM default, not yours.</p><p>Both paths return START_SUCCESS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nS_6NkVxSSwnyDKGx518qw.png" /></figure><h3>Why This Matters More in 2025–2026 Than It Did in 2022</h3><p>Most AAOS production vehicles shipping today — and in active development — run Android 12 or 14. The Renault Scenic E-Tech (2024 production) shipped on Android 12. Android 16 is where Google is; it is not yet where the fleet is.</p><p>What this means practically: every AAOS platform engineer working on a multi-pane build right now is in the Android 12–14 window. This bug is live in their codebase. The fix is not Android 16 Scalable UI — that comes later. The fix available today is CarActivityManager.setPersistentActivity().</p><h3>The Fix: Where Your Android Version Puts You</h3><p>The principle is the same regardless of version: <strong>you must specify the TDA, not just the display.</strong> The API you use to do that depends on your build target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*kgFSVxDNGuawdtt1N7PP2g.png" /></figure><h3>Android 12–14: CarActivityManager.setPersistentActivity()</h3><p>This is the right answer for the majority of engineers reading this article right now:</p><pre>CarActivityManager carActivityManager = car.getCarManager(Car.CAR_ACTIVITY_SERVICE);<br>carActivityManager.setPersistentActivity(<br>    new ComponentName(&quot;com.oem.navigation&quot;, &quot;com.oem.navigation.MapActivity&quot;),<br>    Display.DEFAULT_DISPLAY,<br>    LEFT_PANE_FEATURE_ID   // your OEM&#39;s feature ID for the left pane<br>);</pre><p>setPersistentActivity() registers a binding between a component and a TDA feature ID inside CarLaunchParamsModifier. The fix is persistent — it survives activity restarts and applies even when the activity is launched by a third-party intent.</p><p><strong>Permission required:</strong> PERMISSION_CONTROL_CAR_APP_LAUNCH (system|signature). This is AAOS system app territory. If you&#39;re building at that level and you&#39;re on Android 12–14, this is your API.</p><p>LEFT_PANE_FEATURE_ID is whatever your OEM defined in DisplayAreaPolicy. Run the diagnostic below to find it — the featureId value appears next to each TaskDisplayArea entry in the dumpsys output.</p><h3>Android 16: Scalable UI / TaskPanel</h3><p>Google’s AAOS 25Q2 release targets Android 16 (API level 36) and introduces Scalable UI as the windowing framework that gives OEMs configurable components for pane layout. The TaskPanel model replaces manual TDA wiring with a declarative approach:</p><pre>TaskPanelManager taskPanelManager = carUiController.getTaskPanelManager();<br>TaskPanel leftPanel = taskPanelManager.createTaskPanel(LEFT_PANE_FEATURE_ID);<br>leftPanel.setDefaultComponent(new ComponentName(&quot;com.oem.navigation&quot;, &quot;...MapActivity&quot;));</pre><p>TDA resolution is handled by the framework. You declare panels and components; you never touch tokens directly. This is where AAOS windowing is going — if your program targets Android 16, adopt it now rather than building on CarActivityManager and migrating later.</p><h3>The Diagnostic Workflow</h3><p>The featureId values for your OEM&#39;s panes are visible in the dumpsys output under each TaskDisplayArea entry — note the value next to the pane you want before applying any fix.</p><p><strong>Find which TDA your activity actually landed in:</strong></p><pre>adb shell dumpsys activity activities | grep -A 8 &quot;MapActivity&quot;</pre><p>Correctly placed activity:</p><pre>TaskDisplayArea id=1 featureId=1 name=LEFT_PANE<br>  Task id=42 type=standard<br>    Hist #0: ActivityRecord{... com.oem.navigation/.MapActivity}</pre><p>Misplaced activity (setLaunchDisplayId only):</p><pre>TaskDisplayArea id=2 featureId=2 name=DefaultTaskDisplayArea<br>  Task id=42 type=standard<br>    Hist #0: ActivityRecord{... com.oem.navigation/.MapActivity}</pre><p>featureId=2 when you expected featureId=1 is the signature. This is how you confirm the bug before applying the fix.</p><p><strong>Confirm the token was absent at launch:</strong></p><pre>adb shell wm logging enable-text TAG ActivityTaskManager</pre><p>Relaunch, then look for a log line indicating launchTaskDisplayArea is null. That confirms the activity was routed by getDefaultTaskDisplayArea() rather than an explicit token.</p><p><strong>Distinguish from a z-order issue.</strong> If you’re unsure whether the problem is pane placement or window layering, run:</p><pre>adb shell dumpsys SurfaceFlinger | grep -E &quot;Layer|Z=|com.oem&quot;</pre><p>Correct z-order but wrong screen region = TDA bug. Wrong z-order = look elsewhere.</p><h3>The Systemic Mental Model</h3><p><strong>A display is not a pane.</strong></p><p>setLaunchDisplayId() routes the activity to the physical display — a hardware routing promise the framework keeps completely. What happens after the activity arrives on that display is decided by getDefaultTaskDisplayArea(), which reads OEM configuration you don&#39;t control, that varies between hardware builds, hardware revisions, and sometimes between software versions of the same hardware.</p><p>The moment your layout has more than one TDA per display — which is true of every wide-format, L-shaped, and split-console arrangement — setLaunchDisplayId() is not a placement API. It is a delivery API. It gets the package to the building. It does not find the office.</p><p>Part 1 revealed that the IPC return path, not the sensor, was carrying stale data. Part 2 revealed that process cold-start, not the camera signal, was producing the delay. Here the fix is launch-time specification. The framework faithfully executes the commands it receives. The job is to give it the complete address.</p><h3>What to Check on Your Build Today</h3><p>If you ship an AAOS product with a multi-pane center console, run this now:</p><pre>adb shell dumpsys activity activities | grep -E &quot;TaskDisplayArea|featureId&quot;</pre><p>Count the distinct TaskDisplayArea entries on your center console display. More than one means every setLaunchDisplayId()-only launch in your codebase is relying on OEM default configuration — configuration you don&#39;t own and that can silently change with any DisplayAreaPolicy update, hardware revision, or OEM partner handoff.</p><p>Fix it before the next hardware bring-up reveals it in a parking lot on first boot.</p><p><em>Note: This article covers AAOS — Android running natively on the vehicle’s hardware. Android Auto (phone projection) handles its UI entirely differently via </em><em>VirtualDisplay and embedded </em><em>TaskView. The WindowManager routing described here is AAOS-only.</em></p><h3>Key AOSP References</h3><ul><li><a href="https://cs.android.com/android/platform/superproject/+/android-latest-release:frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java;l=1?q=frameworks%2Fbase%2Fservices%2Fcore%2Fjava%2Fcom%2Fandroid%2Fserver%2Fwm%2FActivityStarter.java">frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java</a> — startActivityInner(), resolveToTaskDisplayArea()</li><li><a href="https://cs.android.com/android/platform/superproject/+/android-latest-release:frameworks/base/services/core/java/com/android/server/wm/DisplayContent.java;l=1?q=frameworks%2Fbase%2Fservices%2Fcore%2Fjava%2Fcom%2Fandroid%2Fserver%2Fwm%2FDisplayContent.java&amp;sq=">frameworks/base/services/core/java/com/android/server/wm/DisplayContent.java</a> — getDefaultTaskDisplayArea()</li><li><a href="https://cs.android.com/android/platform/superproject/+/android-latest-release:frameworks/base/services/core/java/com/android/server/wm/DisplayAreaPolicy.java;l=1?q=frameworks%2Fbase%2Fservices%2Fcore%2Fjava%2Fcom%2Fandroid%2Fserver%2Fwm%2FDisplayAreaPolicy.java">frameworks/base/services/core/java/com/android/server/wm/DisplayAreaPolicy.java</a> — OEM pane layout configuration</li><li><a href="https://cs.android.com/android/platform/superproject/+/android-latest-release:packages/services/Car/car-lib/src/android/car/app/CarActivityManager.java;l=1?q=packages%2Fservices%2FCar%2Fcar-lib%2Fsrc%2Fandroid%2Fcar%2Fapp%2FCarActivityManager.java&amp;sq=">packages/services/Car/car-lib/src/android/car/app/CarActivityManager.java</a> — setPersistentActivity()</li><li><a href="https://cs.android.com/android/platform/superproject/+/android-latest-release:frameworks/opt/car/services/builtInServices/src/com/android/server/wm/CarLaunchParamsModifier.java;l=1?q=CarLaunchParamsModifier.java&amp;sq=">frameworks/opt/car/services/builtInServices/src/com/android/server/wm/CarLaunchParamsModifier.java</a> — persistent placement implementation</li><li><a href="https://cs.android.com/android/platform/superproject/+/android-latest-release:frameworks/base/core/java/android/app/ActivityOptions.java;l=1?q=ActivityOptions.jav">frameworks/base/core/java/android/app/ActivityOptions.java</a>, KEY_LAUNCH_TASK_DISPLAY_AREA_TOKEN</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1789ae0dc34" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/the-window-manager-lied-politely-f1789ae0dc34">The Window Manager Lied Politely</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Surface That Was Too Big]]></title>
            <link>https://proandroiddev.com/the-surface-that-was-too-big-d5a9e09a5051?source=rss-3e5dc36b2b8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5a9e09a5051</guid>
            <category><![CDATA[graphic-design]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[automotive]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Rohith Gaddam]]></dc:creator>
            <pubDate>Sat, 28 Mar 2026 15:51:21 GMT</pubDate>
            <atom:updated>2026-03-28T15:51:45.646Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Android Automotive System Internals — GPU Memory and Composition on AAOS</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*003FdEyTEs12ZHzE" /><figcaption>Photo by <a href="https://unsplash.com/@iamrohitchoudhari?utm_source=medium&amp;utm_medium=referral">Rohit Choudhari</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The vehicle looked fine on screen.</p><p>The 3D model was rendering. The launcher card showed exactly what the designer intended. The QA checklist had a green checkmark next to it.</p><p>Then a colleague asked a simple question: “What size surface are we actually handing to the GPU?”</p><p>We looked. It was nearly five times what the design specified.</p><p>It had been shipping that way for months.</p><h3>A Figma Spec and a TextureView</h3><p>The AAOS infotainment launcher hosts multiple views simultaneously. One of them renders a real-time 3D vehicle view — a live model of the car sitting in a card on the home screen. Under the hood, this means a TextureView connected to an OEM-integrated native 3D rendering SDK via a shared buffer queue. The SDK writes frames into the buffer. Android composites that buffer onto the display.</p><p>Simple enough.</p><p>The Compose code that had been in production looked like this:</p><pre>TextureViewOverlay(<br>    modifier = Modifier.fillMaxSize(),<br>    activity = activity,<br>    onReady = vehicleStatusViewAction,<br>)</pre><p>fillMaxSize(). Fill the container. Simple. Obvious.</p><p>Wrong.</p><h3>What TextureView Actually Allocates</h3><p>Every TextureView is backed by a SurfaceTexture, which sits on a BufferQueue. When you set the size of a TextureView, you are not just telling the layout system how large to draw it. <strong>You are telling the graphics pipeline how many pixels to allocate in GPU memory.</strong> The formula is exact:</p><pre>GPU memory = 3 buffers × width × height × 4 bytes</pre><p>Triple buffering exists to prevent frame tearing. All three buffers are sized to the TextureView dimensions and allocated before first render — not when the rendering SDK connects, not when the first frame appears.</p><blockquote><strong>A note on Android 15 Adaptive Refresh Rate (ARR):</strong> In AAOS, the system may throttle the display refresh rate to 30Hz or 1Hz on static screens. Bus bandwidth usage drops with refresh rate, but the GPU memory allocation remains fixed — Gralloc allocates those buffers upfront at surface creation regardless of refresh rate. The cost model in this article remains fully accurate under ARR.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WU4kpQG-WtqeUfNrmdE66g.png" /></figure><p>Consider a typical AAOS launcher view: a full-width card spanning a 1080×700dp container at 2.75× density, hosting a 3D vehicle view whose design spec calls for a 320×480dp surface. With fillMaxSize, the TextureView allocates at the full container size:</p><pre>fillMaxSize:  3 × 2970 × 1925 × 4 = 68.6 MB<br>Correct size: 3 ×  880 × 1320 × 4 = 13.9 MB</pre><p>54.7 MB wasted. Per view. From one modifier.</p><p>Empty pixels are not free. A TextureView with nothing rendered into it costs exactly as much GPU memory as one fully filled with content. The buffer is allocated at the full TextureView dimensions, regardless of what the rendering SDK does with it.</p><h3>The Rendering Pipeline Nobody Draws</h3><p>There is a second cost that is harder to see.</p><p>TextureView sits inside the Android view hierarchy. This is its great flexibility — you can animate it, fade it, apply transforms to it just like any other view. But this flexibility comes with a compositing price that fires on every single frame.</p><p>In AAOS infotainment systems, 3D vehicle views are typically rendered by an OEM-integrated native rendering SDK that connects to the Android UI layer via a shared BufferQueue. That SDK has no visibility into the Android view hierarchy&#39;s compositing model — it simply writes frames into the buffer it was handed. What happens after that is Android&#39;s responsibility.</p><p>And what happens after that costs far more than it needs to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fMPzs1oe17pDc4PIsAVZ-w.png" /></figure><p>With TextureView, every frame passes through the GPU twice: once when the GL compositor blends the TextureView content into the app UI layer, and once when SurfaceFlinger composites the final display. With SurfaceView, the rendering SDK&#39;s buffer goes directly to a hardware overlay plane — one pass, no intermediate blend.<br>This is not a theoretical concern. The Chromium team documented exactly this tradeoff when switching their Android compositor from TextureView to SurfaceView: TextureView always composites using GL, while SurfaceView can be backed by a hardware overlay which uses less memory bandwidth and power.</p><p>At the dimensions above, the difference is immediate:</p><pre>fillMaxSize TextureView:  2970×1925 × 2 × 60fps = 685M pixels/sec<br>Fixed-size TextureView:    880×1320 × 2 × 60fps = 139M pixels/sec</pre><p>SurfaceView is the architecturally correct path for high-frequency rendered content in Android. The catch: the rendering SDK has to expose a SurfaceView-compatible surface path. Not all embedded 3D SDKs do. Verify with your SDK team before treating migration as an option.</p><p>For a TextureView-only SDK, the composition cost is fixed and unavoidable. What you <em>can</em> control is the surface size — and that directly determines the per-frame cost.</p><h3>The Composition Cost Does Not Scale With Render Rate</h3><p>One subtlety worth understanding before you conclude this only matters for high-frequency 3D content.</p><p>The GL composition pass happens at the <strong>display refresh rate</strong>, not the rendering SDK’s frame rate. Even if your 3D engine is rendering at 1fps — a rotating idle animation, a static vehicle pose — SurfaceFlinger wakes on every VSYNC and composites your TextureView into the app UI layer. 60 times per second. Because the display refreshes 60 times per second, and your TextureView is declared as part of the UI hierarchy it must process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXmzKByIofVvfUdMjM2IKQ.png" /></figure><p>The only thing the rendering frame rate affects is how often the buffer contents change. The composition cost is fixed from surface creation, determined entirely by the TextureView dimensions.</p><p>A correctly sized TextureView reduces the pixel count in every one of those 60 composition passes per second, for the duration of every drive.</p><h3>The Measurement</h3><p>Diagnosing this correctly requires measuring what the rendering SDK actually receives — not what the layout system reports, not what dumpsys meminfo shows.</p><p>dumpsys meminfo captures the entire process. On a vehicle with a shared rendering service managing multiple view instances simultaneously, that number includes the SDK runtime, 3D asset data, shader cache, and all active instances. It is too noisy to isolate a single surface.</p><p>The right measurement is one callback:</p><pre>override fun onSurfaceTextureAvailable(st: SurfaceTexture, w: Int, h: Int) {<br>    if (BuildConfig.DEBUG) {<br>        Log.d(&quot;SurfaceSize&quot;, &quot;surface w=$w h=$h&quot;)<br>    }<br>    connectRenderer()<br>}</pre><p>This reports the exact pixel dimensions handed to the SDK at connection time. No inference. No process-level noise.</p><p>Capture it:</p><pre>adb shell am force-stop &lt;your.package&gt;<br>adb logcat | grep SurfaceSize</pre><p>Compare the reported dimensions against your Figma spec converted to pixels at your device’s actual density. If they don’t match, you have a surface sizing problem.</p><blockquote><strong>Always measure on your actual target hardware.</strong> Automotive HUs vary significantly in screen density — commonly between 1.0× and 2.75×. Back-calculate your device’s density from the measured pixel values before drawing conclusions: density = measured_px ÷ dp_spec. Numbers from a flagship phone benchmark will not transfer.</blockquote><h3>Why the Rendering SDK Cannot Save You</h3><p>The intuition that leads engineers astray: <em>“The SDK only renders into the area it uses. The rest is transparent. Does the surface size actually matter?”</em></p><p>Yes. The BufferQueue allocates at the full TextureView dimensions. The rendering SDK receives a surface of whatever size you gave it — it cannot negotiate a smaller buffer internally. Hand it a 2970×1925px surface and that is what gets allocated. SurfaceFlinger composites the full rectangle on every VSYNC regardless of how much of it contains rendered content.</p><blockquote>In many AAOS implementations, Gralloc buffers are allocated from the Contiguous Memory Allocator (CMA) — a fixed-size physical memory pool shared across the entire SoC. Unlike heap memory, CMA cannot be reclaimed or paged. An oversized surface doesn’t just consume memory — it consumes contiguous physical memory. On a constrained automotive SoC, that pool is shared with the Rear View Camera pipeline, the video decoder, and other hardware-backed buffers. Waste enough of it with incorrectly sized surfaces and initialization of safety-adjacent components can fail — not gracefully degrade, fail.</blockquote><h3>The Fix</h3><pre>// Before — fills entire container, oversized surface passed to rendering SDK<br>TextureViewOverlay(<br>    modifier = Modifier.fillMaxSize(),<br>    activity = activity,<br>    onReady = vehicleStatusViewAction,<br>)<br><br>// After - sized to design specification, not container<br>// 3D vehicle view is sized and anchored per Figma spec (right-aligned).<br>// Dimensions sourced from dimens.xml - do not use fillMaxSize here.<br>TextureViewOverlay(<br>    modifier = Modifier<br>        .align(Alignment.CenterEnd)<br>        .width(Theme.dimens.vehicleViewWidth)<br>        .height(Theme.dimens.vehicleViewHeight),<br>    activity = activity,<br>    onReady = vehicleStatusViewAction,<br>)</pre><pre>&lt;!-- dimens.xml — sourced directly from Figma spec --&gt;<br>&lt;dimen name=&quot;vehicle_view_width&quot;&gt;320dp&lt;/dimen&gt;<br>&lt;dimen name=&quot;vehicle_view_height&quot;&gt;480dp&lt;/dimen&gt;</pre><p>The comment is intentional. It documents design intent and prevents the next engineer from reverting to fillMaxSize assuming it is a bug fix.</p><p>The design team specified an exact surface. The implementation had been ignoring that specification entirely — and the GPU had been paying for it on every drive.</p><h3>Pro-tip: Force Buffer Dimensions Directly on SurfaceTexture</h3><p>If your rendering SDK connects via SurfaceTexture and you cannot change the TextureView layout size — for example, if it is controlled by a third-party component — there is a lower-level lever available: setDefaultBufferSize().</p><p>This method sets the internal buffer dimensions on the SurfaceTexture directly, independent of the view&#39;s layout dimensions. The GPU allocates only the buffer you specify. The hardware scaler handles stretching the content to fill the view rectangle — at a fraction of the cost of allocating and compositing a full-sized buffer.</p><pre>override fun onSurfaceTextureAvailable(st: SurfaceTexture, w: Int, h: Int) {<br>    // Override the internal buffer size to match the 3D content spec,<br>    // not the view layout dimensions. GPU allocates only what the SDK needs.<br>    // Hardware scaler handles the stretch — no full-size buffer required.<br>    st.setDefaultBufferSize(<br>        resources.getDimensionPixelSize(R.dimen.vehicle_view_width),<br>        resources.getDimensionPixelSize(R.dimen.vehicle_view_height)<br>    )<br>    if (BuildConfig.DEBUG) {<br>        Log.d(&quot;SurfaceSize&quot;, &quot;buffer forced to: &quot; +<br>            &quot;${resources.getDimensionPixelSize(R.dimen.vehicle_view_width)}x&quot; +<br>            &quot;${resources.getDimensionPixelSize(R.dimen.vehicle_view_height)}&quot;)<br>    }<br>    connectRenderer()<br>}</pre><p>Use this as a safety net, not a primary fix. The correct approach remains sizing the TextureView to its design specification. setDefaultBufferSize() is the right tool when the view size is genuinely outside your control.</p><h3>Modern Path: AndroidExternalSurface (Android 14+)</h3><p>If your rendering SDK can accept a raw Surface — rather than requiring a SurfaceTexture — Android 14 introduced AndroidExternalSurface, the modern Jetpack Compose wrapper around SurfaceView. It eliminates the GL composition pass entirely by giving SurfaceFlinger a dedicated hardware overlay plane for your content.</p><pre>// AndroidExternalSurface — hardware overlay path (API 34+)<br>// Only use this if your SDK accepts a raw Surface.<br>// SDKs that connect via SurfaceTexture (including some Unreal configurations)<br>// cannot use this path — they require TextureView.<br>AndroidExternalSurface(<br>    modifier = Modifier<br>        .align(Alignment.CenterEnd)<br>        .width(Theme.dimens.vehicleViewWidth)<br>        .height(Theme.dimens.vehicleViewHeight)<br>) {<br>    onSurface { surface, width, height -&gt;<br>        // Surface is managed by SurfaceFlinger as a separate HWC overlay plane.<br>        // No GL compositor pass in the app process — one GPU pass only.<br>        connectRenderer(surface)<br><br>        surface.onChanged { newWidth, newHeight -&gt;<br>            if (BuildConfig.DEBUG) {<br>                Log.d(&quot;SurfaceSize&quot;, &quot;surface w=$newWidth h=$newHeight&quot;)<br>            }<br>        }<br><br>        surface.onDestroyed {<br>            disconnectRenderer()<br>        }<br>    }<br>}</pre><p><strong>The critical distinction:</strong> TextureView connects via SurfaceTexture (a GLES texture path). AndroidExternalSurface and SurfaceView expose a raw Surface (a direct BufferQueue path to SurfaceFlinger). These are different surface types — your SDK determines which one it can accept, not your Compose wrapper. If your SDK only supports SurfaceTexture, AndroidExternalSurface is not available to you regardless of how it is wrapped. Verify the surface type your SDK requires before treating migration as an option.</p><p>When AndroidExternalSurface is available, the composition cost comparison becomes:</p><pre>TextureView (fixed size):       880×1320 × 2 × 60fps = 139M pixels/sec<br>AndroidExternalSurface:         880×1320 × 1 × 60fps =  69.7M pixels/sec</pre><p>Half the composition cost, no GL middleman, and a dedicated hardware overlay plane. For SDKs that support it, this is the correct end state.</p><h3>Why This Compounds on Automotive Hardware</h3><p>A phone has one screen, and it sleeps after thirty seconds. An AAOS launcher hosts multiple views, several potentially running 3D content simultaneously, and it runs for the duration of every drive.</p><p>Each TextureView follows the same cost model independently:</p><pre>Per TextureView:  3 buffers × w × h × 4 bytes  (always allocated)<br>Per frame:        pixels × 2 GL passes × 60fps  (always paid)</pre><p>These costs are additive. Every incorrectly sized TextureView on the launcher screen contributes its own buffer allocation and its own independent GL blend pass on every VSYNC — regardless of what every other view is doing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sArBhqYbhq1F2jaYhT1pQw.png" /></figure><p>For a single view, the numbers are already significant: 54.7 MB of unnecessary GPU buffer allocation, 546M pixels per second eliminated from the composition pipeline. Every additional incorrectly sized TextureView on the screen adds the same burden at its own scale.</p><p><strong>There is an additional constraint specific to automotive hardware worth understanding: Hardware Composer overlay planes.</strong></p><p>Most automotive SoCs — including the Qualcomm SA8155P and SA8295 — have a limited number of hardware overlay planes, typically four to eight. SurfaceView and AndroidExternalSurface consume one overlay plane each. If the system runs out of overlay planes, the Hardware Composer falls back to GPU composition for everything — including views that were previously on hardware overlays. At that point, you have lost the benefit of the hardware path and added GPU composition pressure on top of your existing TextureView costs.</p><p>This makes surface sizing discipline even more important. You are not just managing GPU memory and composition cost — you are managing a finite hardware resource that the entire system shares, including the cluster display and any Driver Monitoring System running on the same SoC.</p><p>The automotive GPU is not a flagship phone GPU. It is a fixed-capability chip running for hours under sustained load, without the thermal relief of a screen lock or a sleep cycle. On a phone, this kind of inefficiency shows up as battery drain you might not notice. On automotive hardware, running continuously against a fixed GPU budget, it shows up as thermal throttling, frame drops, and competition with every other process that needs the GPU — including the ones responsible for safety-critical rendering.</p><h3>The Platform Principle</h3><p>TextureView sizing is not a micro-optimization. It is a correctness issue.</p><p>The design team specified exact dimensions for a reason. When the implementation ignores those dimensions and uses fillMaxSize instead, it is not just wasting GPU memory — it is handing the rendering SDK a surface larger than the design intended, allocating memory that was never needed, and paying a composition cost on every frame that was never necessary.</p><p>Before you move on: search your project for TextureView and fillMaxSize appearing within a few lines of each other. Check each one against its design specification. Measure the actual dimensions with onSurfaceTextureAvailable. The measurement takes five minutes.</p><p>The fix is one modifier chain. The savings compound across every view on the screen, every second of every drive.</p><p><strong>Every surface should be exactly as large as the content it contains — no larger.</strong></p><h3>How to Verify on Your Device</h3><pre>// 1. Add to onSurfaceTextureAvailable<br>override fun onSurfaceTextureAvailable(st: SurfaceTexture, w: Int, h: Int) {<br>    if (BuildConfig.DEBUG) {<br>        Log.e(&quot;SurfaceSize&quot;, &quot;surface w=$w h=$h&quot;)<br>    }<br>}</pre><pre># 2. Force cold start and capture<br>adb shell am force-stop &lt;your.package&gt;<br>adb logcat | grep SurfaceSize<br><br># 3. Find your rendering service process<br>adb shell ps -A | grep -i &quot;render\|engine\|3d\|avatar&quot;<br># 4. Inspect SurfaceFlinger layer allocation<br>adb shell dumpsys SurfaceFlinger | grep -A10 &quot;&lt;your layer name&gt;&quot;</pre><blockquote><strong>Important:</strong> If the rendering SDK manages its own EGL surfaces directly, GPU buffer allocations may not appear in dumpsys meminfo under standard EGL/Gfx categories. Use onSurfaceTextureAvailable dimensions as the primary measurement — it directly reports what the SDK receives.</blockquote><p><em>This article is a companion piece to the Android Automotive System Internals series.</em></p><ul><li><em>Part 1: </em><a href="https://proandroiddev.com/the-speedometer-lied-debugging-real-time-ipc-in-android-automotive-0323df7d6234"><em>The Speedometer Lied — Debugging Real-Time IPC in Android Automotive</em></a></li><li><em>Part 2: </em><a href="https://proandroiddev.com/the-camera-that-launched-too-late-51717ac85c0d"><em>The Camera That Launched Too Late</em></a></li></ul><h3>References</h3><ul><li><a href="https://source.android.com/docs/core/graphics/architecture">AOSP Graphics Architecture</a> — the BufferQueue pipeline in detail</li><li><a href="https://source.android.com/docs/core/graphics/arch-bq-gralloc">BufferQueue and Gralloc</a> — buffer allocation mechanics; confirms allocation is sized at surface creation</li><li><a href="https://groups.google.com/a/chromium.org/g/graphics-dev/c/Z0yE-PWQXc4?pli=1">Chromium Graphics Dev — Use TextureView as compositing surface on Android?</a> — Sami Kyostila (Google) independently confirms the triple-buffer formula (3 × view_width × view_height × 4 bytes) and documents why Chrome switched from TextureView to SurfaceView: GL-only composition vs hardware overlay, higher memory bandwidth, and additional buffering latency</li><li><a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/viewinterop/package-summary#AndroidExternalSurface">AndroidExternalSurface — Jetpack Compose API</a> — modern Compose wrapper for hardware overlay surface path (API 34+)</li><li><a href="https://developer.android.com/reference/android/graphics/SurfaceTexture#setDefaultBufferSize(int,%20int)">SurfaceTexture.setDefaultBufferSize</a> — force internal buffer dimensions independent of view layout size</li><li><a href="https://developer.android.com/media/media3/ui/surface">Android Media3 Surface documentation</a> — SurfaceView recommendation for video playback</li><li><a href="https://perfetto.dev/docs/quickstart/android-tracing">Perfetto tracing quickstart</a> — for GPU composition measurement</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5a9e09a5051" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/the-surface-that-was-too-big-d5a9e09a5051">The Surface That Was Too Big</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Camera That Launched Too Late]]></title>
            <link>https://proandroiddev.com/the-camera-that-launched-too-late-51717ac85c0d?source=rss-3e5dc36b2b8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/51717ac85c0d</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[android-automotive]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Rohith Gaddam]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 17:06:56 GMT</pubDate>
            <atom:updated>2026-03-03T18:30:30.284Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Android Automotive System Internals — Part 2: ActivityManagerService &amp; Lifecycle Orchestration</em></p><p>The speedometer problem was solved.</p><p>Binder was behaving. Threads were stable. IPC was clean.</p><p>Then we shifted into reverse.</p><p>And the screen stayed black.</p><p>Not frozen. Not crashed. Just <strong>late</strong>.</p><p><strong>Eight hundred milliseconds late.</strong></p><h3>Why 800ms Is an Engineering Emergency</h3><p>Before diving into traces, the regulatory context matters.</p><p><strong>FMVSS 111</strong> — the U.S. federal safety standard for rear visibility — mandates that the camera image must be visible within <strong>2.0 seconds</strong> of the driver shifting into reverse. If you miss this window, you do not ship the car. It is a hard gating requirement.</p><p>Two seconds sounds generous. It isn’t. By the time you account for CAN bus propagation, VHAL processing, CarService policy evaluation, and the UI orchestration chain we’re about to trace, 800ms of ActivityManager overhead consumes <strong>40% of your entire compliance budget</strong> before a single pixel appears.</p><p>What made this tricky: every usual suspect came back innocent. The reverse signal was correct. The policy fired. The intent was dispatched. The delay lived somewhere else — inside the activity/task/window machine that brings pixels to the screen.</p><p>When you transition from an RTOS — where UI updates are near-instantaneous — to AAOS, the reality of ActivityManagerService, Zygote forks, and Window orchestration hits hard. That collision is what this article is about.</p><h3>First: Know Which Problem You’re Debugging</h3><p>Most articles on RVC latency skip this boundary. Don’t.</p><p><strong>If the driver shifts into reverse within seconds of cold-booting the vehicle</strong>, Android’s framework will never be fast enough. AOSP addresses this through the <strong>EVS (Exterior View System) HAL</strong> — a C++ layer that streams camera frames directly to the display, bypassing ActivityManager, SurfaceFlinger, and CarService entirely until user space is ready.</p><p>If you’re debugging cold-boot camera latency, you’re in the wrong layer. You need the EVS HAL, not activity traces.</p><p><strong>This article is about runtime RVC</strong>: the OS is fully running, the driver shifts into reverse during normal operation. EVS is dormant. The Activity framework is in charge. That’s where the 800ms lives.</p><h3>The Architecture of a Shift</h3><p>The instinct when you first work with AAOS: “camera in reverse = launch an activity.” One intent, one hop.</p><p>That mental model breaks the moment you trace it.</p><p>What actually happens when a driver shifts into reverse is better described as <strong>advancing a distributed state machine across five service boundaries</strong>, each with its own Binder domain and thread pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*m7BpfLo66mRLyy0wnZAp9A.png" /><figcaption><strong>Figure 1.</strong> The full orchestration chain from VHAL to pixels. Each arrow is a Binder transaction or internal service call. The dashed path is the cold start route — where 800ms hides.</figcaption></figure><p>The chain begins in the VHAL. When the CAN bus broadcasts a gear change, the VHAL emits VehicleProperty::GEAR_SELECTION (Property ID: 0x11400400). One critical detail: <strong>this property&#39;s change mode must be </strong><strong>ON_CHANGE, not continuous</strong>. If your framework is polling the VHAL for gear state on a timer, you have already lost the latency battle before the UI knows anything has happened.</p><p>At the application layer, your CarPropertyManager callback fires:</p><pre>carPropertyManager.registerCallback(<br>    object : CarPropertyEventCallback {<br>        override fun onChangeEvent(value: CarPropertyValue&lt;*&gt;) {<br>            val gear = value.value as Int<br>            if (gear == VehicleGear.GEAR_REVERSE) {<br>                launchRearViewCamera()  // Time is ticking.<br>            }<br>        }<br>        override fun onErrorEvent(propId: Int, zone: Int) {<br>            Log.e(TAG, &quot;VHAL error: $propId&quot;)<br>        }<br>    },<br>    VehiclePropertyIds.GEAR_SELECTION,<br>    CarPropertyManager.SENSOR_RATE_ONCHANGE  // Event-driven, not polled<br>)</pre><p>Once launchRearViewCamera() fires, control passes to ActivityManagerService. This is where our 800ms went.</p><h3>Tracing the Gap</h3><p>For AAOS UI latency, logcat tells you <em>that</em> something is slow. Perfetto tells you <em>where</em> the time went. You need a unified timeline of the CPU scheduler, Binder transactions, and Window Manager in a single view.</p><p>Capture three signals simultaneously:</p><ul><li><strong>sched_switch</strong> — shows when critical threads are runnable but not actually scheduled. A RUNNABLE thread sitting idle is a scheduling policy problem, not an app bug.</li><li><strong>am / </strong><strong>wm atrace categories</strong> — exposes ActivityManager and WindowManager internal state transitions as named slices.</li><li><strong>binder_driver</strong> — confirms whether cost is in orchestration or IPC queueing.</li></ul><pre>./record_android_trace -o rvc_launch.perfetto-trace -t 10s -b 32mb \<br>  sched freq idle am wm gfx binder_driver hal camera</pre><p>Shift into reverse during capture. Load the trace at <a href="https://ui.perfetto.dev/">ui.perfetto.dev</a> and anchor on ActivityTaskManager slices within the am category.</p><h3>What the Trace Actually Shows</h3><p>Here’s the concrete breakdown from a trace on this problem. The numbers are representative of this class of issue — measure your own hardware, but expect this pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*2o7vqsuHHo_FWne1brN9iQ.png" /><figcaption><strong><em>Figure 2.</em></strong><em> Warm start completes in ~150ms and is FMVSS-compliant. Cold start reaches 800ms+ — consuming most or all of the regulatory budget — because the process was killed by lmkd between shifts.</em></figcaption></figure><p><strong>Warm start (process alive):</strong></p><pre>T+0   ms  Reverse event recognized<br>T+15  ms  CarPropertyManager callback fires<br>T+30  ms  am resolves target, routes to existing task<br>T+80  ms  wm applies focus + transition<br>T+150 ms  First pixel on screen ✓</pre><p><strong>Cold start (process killed by lmkd):</strong></p><pre>T+0   ms  Reverse event recognized<br>T+15  ms  CarPropertyManager callback fires<br>T+300 ms  Zygote finishes forking the RVC process<br>T+450 ms  Activity.onCreate() + onResume() complete<br>T+800 ms  SurfaceFlinger composites the first camera frame</pre><p>The brutal detail in that cold start timeline: <strong>the Activity was “resumed” at T+450ms, but the driver saw nothing until T+800ms.</strong> There’s a 350ms gap between “the framework thinks we’re done” and “pixels on glass.” That’s the camera HAL initialization and surface buffer fill cost — and it’s invisible until you instrument reportFullyDrawn() separately from Displayed.</p><p>The Zygote fork alone is 200–400ms on automotive silicon. That cost runs before a single line of your application code executes.</p><h3>Solution 1: Keep the Process Warm</h3><p>If your trace shows the delay dominated by Zygote fork + bindApplication, the fix is not to optimize those operations. The fix is to ensure the process is never dead when reverse fires.</p><h3>The true cost of android:persistent=&quot;true&quot;</h3><p>You might reach for this in the manifest:</p><pre>&lt;application android:persistent=&quot;true&quot; android:process=&quot;:rear_camera&quot; /&gt;</pre><p>In a standard Android app, the OS silently ignores this. In AAOS, <strong>three system-level requirements must all be met</strong> before the flag is honored:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*XS9xvHEUOSJFOcHbvgkS0w.png" /><figcaption><strong>Figure 3.</strong> The manifest flag alone does nothing. All three requirements must be satisfied — and when they are, lmkd assigns an oom_adj of approximately -800 to -1000, meaning the process lives for the lifetime of the user session.</figcaption></figure><p><strong>① APK location</strong> — the app must be installed as a privileged system app in /system/priv-app/ or /vendor/priv-app/. Not in the data partition.</p><p><strong>② privapp-permissions.xml whitelist</strong> — the package must be explicitly declared in etc/permissions/privapp-permissions.xml:</p><pre>&lt;privapp-permissions package=&quot;com.oem.car.camera&quot;&gt;<br>    &lt;permission name=&quot;android.car.permission.CAR_POWERTRAIN&quot;/&gt;<br>&lt;/privapp-permissions&gt;</pre><p><strong>③ Platform certificate</strong> — the APK must be signed with the platform key, not a standard developer keystore.</p><p>Verify the configuration actually worked:</p><pre>adb shell dumpsys activity processes | grep -A3 &quot;rear_camera&quot;<br># oom_adj should be -800 or lower.<br># If it&#39;s above 0, the persistence config failed silently.</pre><p><strong>The tradeoff is real.</strong> Memory allocated to this process — camera pipeline, rendering surfaces, class-loaded code — is permanently unavailable to other apps. In a vehicle with fixed hardware where RVC is safety-critical, this is usually the right call. Evaluate it deliberately.</p><h3>Pre-warm as an alternative</h3><p>For builds where full persistence is too aggressive, start the RVC process on ignition or user unlock:</p><ul><li>Initialize class loading and open the camera session early — session open is often the most expensive single operation in onCreate().</li><li>Pre-allocate a SurfaceView or TextureView in a hidden state so the buffer is waiting when onResume() fires.</li><li>Keep the process warm without permanently pinning it against memory pressure.</li></ul><h3>Solution 2: Force Predictable Task Reuse</h3><p>Even with a warm process, you need the task stack to behave predictably across repeated reverse events.</p><pre>&lt;activity<br>    android:name=&quot;.RearViewCameraActivity&quot;<br>    android:launchMode=&quot;singleTask&quot; /&gt;</pre><p>Pair this with FLAG_ACTIVITY_CLEAR_TOP in the intent:</p><pre>rvcIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)</pre><p>This handles the real-world pattern: reverse → drive → reverse. The second event reuses the existing task instance instead of creating a new stack entry. Without CLEAR_TOP, repeated reverse cycles can accumulate task entries that produce inconsistent launch behavior over time.</p><p><strong>One edge case to test explicitly:</strong> shift reverse → drive → reverse faster than the first launch completes. Watch dumpsys activity activities during rapid changes. If you see task duplication, add a debounce or state guard in the orchestrator before the startActivityAsUser() call.</p><h3>Solution 3: Launch for the Right User</h3><p>This is the detail that silently breaks systems for engineers coming from phone development.</p><p>AAOS uses <strong>Headless System User Mode (HSUM)</strong>. System services run as User 0. The driver’s UI runs as User 10 (or another non-zero profile). If you call context.startActivity() from a system context without specifying the target user, the activity may launch for User 0 — which has no visible display surface. You get no error, no crash, just nothing on screen.</p><pre>context.startActivityAsUser(rvcIntent, options.toBundle(), UserHandle.CURRENT)</pre><p>UserHandle.CURRENT routes to the visible user&#39;s UI space. Always specify it explicitly when launching from system context.</p><h3>Quick Verification Commands</h3><p>Three commands to run before you reach for Perfetto:</p><pre># Is the process alive? What&#39;s its oom_adj?<br># If oom_adj is high, lmkd killed it before the reverse event.<br>adb shell dumpsys activity processes | grep -A3 &quot;rear_camera&quot;<br><br># Is the task on the correct display?<br># Do you have duplicate instances from repeated reverse events?<br>adb shell dumpsys activity activities | grep -A5 &quot;RearViewCamera&quot;<br><br># Baseline launch time - run 20 cycles, check variance not just mean.<br># High variance = cold start randomness. Low variance = consistently warm.<br>adb shell am start-activity -W -n com.oem.camera/.RearViewCameraActivity</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*ZCQwcREQ5HEvw1SvBwaYZw.png" /></figure><h3>Closing</h3><p>Part 1 taught: “working” isn’t the same as “timely.”</p><p>Part 2 narrows that to automotive: the reverse camera can be architecturally correct, compliant on paper, and still fail the driver if the process is cold when reverse fires.</p><p>When RVC is late, one question cuts to the answer:</p><p><strong>Did we pay for IPC, or did we pay for lifecycle?</strong></p><p>If the trace shows Zygote fork dominating, fix the orchestration layer — not the camera driver, not the rendering pipeline:</p><ul><li>Keep the process warm. Understand what persistent=&quot;true&quot; <em>actually</em> requires.</li><li>Force task reuse. singleTask + CLEAR_TOP, not just one or the other.</li><li>Route to the right user. UserHandle.CURRENT — always explicit from system context.</li></ul><p>In vehicles, lifecycle isn’t an app concern.</p><p><strong>Lifecycle is infrastructure.</strong></p><p><em>Part 3 covers WindowManager and multi-display orchestration — what actually happens inside </em><em>wm during the transition, why display targeting without </em><em>setLaunchDisplayId() is unreliable across OEM configurations, and how to keep the cluster display stable while the center console transitions.</em></p><p><strong>Resources</strong></p><p><em>AOSP Source</em></p><ul><li><a href="https://cs.android.com/android/platform/superproject/main/+/main:frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java;l=1?q=activitymanagerservice">ActivityManagerService</a></li><li><a href="https://cs.android.com/android/platform/superproject/+/android-latest-release:frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java">ActivityTaskManagerService</a></li><li><a href="https://cs.android.com/android/platform/superproject/main/+/main:packages/services/Car/car-lib/src/android/car/hardware/property/CarPropertyManager.java">CarPropertyManager</a></li><li><a href="https://cs.android.com/android/platform/superproject/main/+/main:hardware/interfaces/automotive/evs/">Camera HAL</a></li><li><a href="https://cs.android.com/android/platform/superproject/main/+/main:packages/services/Car/cpp/evs/">EVS Manager/Stack</a></li><li><a href="https://source.android.com/docs/core/permissions/perms-allowlist">Privileged app permissions</a></li></ul><p><em>Tools</em></p><ul><li><a href="https://perfetto.dev/docs/quickstart/android-tracing">Perfetto quickstart (Android)</a></li><li><a href="https://ui.perfetto.dev/">Perfetto UI</a></li></ul><p><strong>Related Reading</strong></p><p><em>In this series</em></p><ul><li>Part 1: <a href="https://medium.com/@rohithgd90/the-speedometer-lied-debugging-real-time-ipc-in-android-automotive-0323df7d6234">The Speedometer Lied — Binder IPC &amp; Return-Path Latency</a></li></ul><p><em>Android documentation</em></p><ul><li><a href="https://developer.android.com/topic/performance/vitals/launch-time">App startup time — cold, warm, and hot starts</a></li><li><a href="https://developer.android.com/guide/components/activities/tasks-and-back-stack">Activity launch modes</a></li><li><a href="https://source.android.com/docs/core/display/multi_display/activity-launch">Multi-display activity launch (AOSP)</a></li><li><a href="https://source.android.com/docs/core/architecture/hidl/binder-ipc">Android Binder IPC architecture</a></li><li><a href="https://developer.android.com/cars">AAOS developer guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51717ac85c0d" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/the-camera-that-launched-too-late-51717ac85c0d">The Camera That Launched Too Late</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Speedometer Lied: Debugging Real-Time IPC in Android Automotive]]></title>
            <link>https://proandroiddev.com/the-speedometer-lied-debugging-real-time-ipc-in-android-automotive-0323df7d6234?source=rss-3e5dc36b2b8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/0323df7d6234</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[android-automotive]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Rohith Gaddam]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 22:37:39 GMT</pubDate>
            <atom:updated>2026-03-03T18:26:28.089Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Android Automotive System Internals — Part 1: Binder IPC &amp; the Return-Path Latency Problem that Shouldn’t Exist</em></p><p>Picture this: a test vehicle on the proving ground, accelerating smoothly through a validation run. Everything feels right — but the digital speedometer on the instrument cluster is frozen, stubbornly displaying 35 mph while the car surges forward. A few seconds pass. Still 35. The vehicle is clearly moving faster, but the display has stopped caring.</p><p>This isn’t a hypothetical. It’s a scenario that surfaces repeatedly in Android Automotive OS (AAOS) development — a frozen or stale gauge reading that defies easy explanation because every individual component, when checked in isolation, appears to be working correctly. The sensor is publishing. The service is running. The app is subscribed. And yet: 35 mph, going nowhere.</p><p>Working in this space, this class of problem comes up more than you’d expect. It’s rarely a single obvious failure. It’s almost always a <strong>timing issue buried inside Android’s multi-layer IPC chain</strong> — and tracing it forces you to understand the architecture at a level most developers never need to reach.</p><p>What follows is a structured walkthrough of exactly that investigation: following a vehicle speed reading from physical sensor to UI, understanding where latency accumulates, and building a mental model that applies to any real-time property in AAOS.</p><p>The speedometer is just the symptom. The real story is about <strong>why Android’s Binder IPC, brilliant for traditional Android, creates fundamental challenges for automotive use cases</strong>.</p><h3>Why AAOS IPC Is Architecturally Different</h3><p>Before diving into the debugging, let’s establish why this problem is uniquely automotive.</p><p>In a typical Android app, IPC delays are annoying but rarely critical. A 200ms delay in loading a notification? The user won’t notice. But in a car traveling at 70 mph, a 200ms speedometer lag means you’re displaying a speed from <strong>20 feet ago</strong>. For safety-critical UIs — speedometers, collision warnings, battery state in EVs — latency isn’t just a performance metric. It’s a correctness issue.</p><p>AAOS inherits Android’s security model: apps are sandboxed, system services mediate hardware access, and everything flows through Binder IPC. This creates a fundamental tension:</p><ul><li><strong>Android’s design goal:</strong> Isolate apps from hardware to prevent malicious access</li><li><strong>Automotive’s requirement:</strong> Stream sensor data at 10–100 Hz with minimal latency</li></ul><p>The result? <strong>A multi-layer IPC chain where each hop adds latency, thread scheduling uncertainty, and potential bottlenecks</strong>. Understanding this chain isn’t optional for automotive platform engineers — it’s the foundation of performance debugging.</p><p>Here’s the complete data flow for a simple vehicle property like speed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHIAoAI1AWwikuubSmqWKQ.jpeg" /></figure><h3>Following the Data Trail</h3><p>Let me show you how I debugged this, layer by layer.</p><h3>Layer 1: The App (Instrument Cluster)</h3><p>Our speedometer app uses Android’s Car API to access vehicle data. The code looked correct:</p><pre>// ClusterActivity.kt - This is where we EXPECTED updates...<br>val carPropertyManager = car.getCarManager(Car.PROPERTY_SERVICE) as CarPropertyManager<br><br>carPropertyManager.registerCallback(object : CarPropertyEventCallback() {<br>    override fun onChangeEvent(value: CarPropertyValue&lt;*&gt;) {<br>        val timestamp = System.currentTimeMillis()<br>        val speed = value.value as Float<br>        Log.d(TAG, &quot;Speed update: $speed mph at $timestamp&quot;)  // &lt;-- NOT FIRING<br>        updateSpeedUI(speed)<br>    }<br>    <br>    override fun onErrorEvent(propId: Int, zone: Int) {<br>        Log.e(TAG, &quot;Speed property error! propId=$propId zone=$zone&quot;)  // &lt;-- Also silent<br>    }<br>}, VehiclePropertyIds.PERF_VEHICLE_SPEED, CarPropertyManager.SENSOR_RATE_NORMAL)</pre><p><strong>First clue:</strong> Neither onChangeEvent nor onErrorEvent was being called. The callback registration succeeded (no exception), but the app was receiving zero updates.</p><p>This told me the problem wasn’t app-side logic. The Binder call to register the callback must have succeeded (otherwise we’d get an exception), but data wasn’t flowing back. Time to go deeper.</p><h3>Layer 2: CarService (The Hidden Middleman)</h3><p>In AAOS, CarService is the gatekeeper for all vehicle data. Apps never talk to the Vehicle HAL directly—they always go through CarService, which:</p><ol><li>Enforces permissions (does this app have CAR_SPEED privilege?)</li><li>Manages subscriptions to vehicle properties</li><li>Batches updates to reduce IPC overhead</li><li>Bridges the security domain boundary between system and vendor</li></ol><p>When our app called registerCallback(), it actually made a Binder call to CarService. I enabled verbose logging:</p><pre>adb shell setprop log.tag.CarService VERBOSE<br>adb logcat -s CarService:V</pre><p><strong>Output:</strong></p><pre>D/CarService: registerListener() propId=0x11600207 rate=1.0 pid=2847<br>D/CarService: Property 0x11600207 available, subscribing to VHAL<br>I/CarService: Successfully subscribed to VHAL for propId=0x11600207</pre><p>Good news: CarService received the subscription request and forwarded it to the VHAL. The Binder hop from app → CarService was working. But why wasn&#39;t the app seeing data?</p><h3>Layer 3: The Vehicle HAL (Hardware Abstraction Layer)</h3><p>The VHAL is where the software meets the hardware. In modern AAOS, it’s implemented as an AIDL interface (IVehicle) running in a separate vendor process. Here&#39;s the critical architectural detail most developers miss:</p><p><strong>CarService and VHAL live in different security domains.</strong></p><ul><li>CarService runs in system_server (system domain, uses /dev/binder)</li><li>VHAL typically runs in a vendor process (vendor domain, may use /dev/hwbinder for HIDL or a vendor-specific AIDL instance)</li></ul><p>This cross-domain communication is <strong>intentional</strong> — it isolates vendor code from the system. But it means our speed data must cross this boundary via Binder IPC, adding another serialization/deserialization step.</p><p>I enabled VHAL logging:</p><pre>adb shell setprop log.tag.VehicleHalImpl VERBOSE<br>adb logcat -s VehicleHalImpl:V</pre><p><strong>Output:</strong></p><pre>V/VehicleHalImpl: subscribe() propId=0x11600207 sampleRate=1.0<br>D/VehicleHalImpl: Polling speed from ECU via CAN<br>D/VehicleHalImpl: Speed changed: 35.0 → 42.3 mph, notifying subscribers<br>D/VehicleHalImpl: onPropertyEvent() propId=0x11600207 value=42.3</pre><p><strong>Critical discovery:</strong> The VHAL was getting fresh speed data and trying to send it back to CarService. The sensor wasn&#39;t the problem. The data was making it from the ECU through the VHAL. So why wasn&#39;t it reaching the app?</p><h3>The Smoking Gun: Binder Thread Pool Exhaustion</h3><p>At this point, I had confirmation that:</p><ul><li>App successfully registered a callback</li><li>CarService subscribed to VHAL</li><li>VHAL was publishing updates</li></ul><p>But the app’s callback wasn’t firing. This pattern pointed to one culprit: <strong>Binder thread pool contention</strong>.</p><p>Here’s what I found in the logs that confirmed it:</p><pre>W/CarPropertyManager: Binder call slow: took 152ms (threshold: 100ms)<br>W/CarPropertyManager: Too many sync requests, sleeping 10ms before retry</pre><p>This warning comes from CarPropertyManager&#39;s client code, which has retry logic for slow Binder responses. It indicated that CarService&#39;s Binder thread pool was temporarily exhausted.</p><p>But here’s the twist: <strong>the real bottleneck wasn’t in </strong><strong>CarService—it was in the app&#39;s own Binder thread pool</strong>.</p><h3>The Real Culprit: Return-Path Latency</h3><p>I used Android’s Perfetto tracing tool to visualize the complete round-trip:</p><pre>adb shell perfetto \<br>  -c - --txt \<br>  -o /data/misc/perfetto-traces/trace \<br>  &lt;&lt;EOF<br>buffers: {<br>    size_kb: 63488<br>    fill_policy: RING_BUFFER<br>}<br>data_sources: {<br>    config {<br>        name: &quot;linux.ftrace&quot;<br>        ftrace_config {<br>            ftrace_events: &quot;binder/binder_transaction&quot;<br>            ftrace_events: &quot;binder/binder_transaction_received&quot;<br>        }<br>    }<br>}<br>EOF</pre><p>The Perfetto trace revealed the issue clearly.</p><blockquote><strong><em>Note on the timeline below:</em></strong><em> The specific millisecond values shown are representative of this class of problem, constructed from known Binder transaction characteristics (baseline ~3–5ms per hop under moderate load, documented by Android’s own hwbinder latency tests) and realistic UI thread scheduling behavior. Actual numbers vary by device, load, and AAOS version. The pattern — fast downward path, delayed return callback — is the real finding. Use </em><em>value.timestampvs </em><em>SystemClock.elapsedRealtimeNanos() in your own callbacks to measure actual latency on your hardware.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yq0QxVZ0rtUgiVN9rUvnaQ.jpeg" /></figure><p><strong>The 174ms gap</strong> between T+106 (data sent) and T+280 (data received) was the problem. The Binder transaction was sitting in the app’s Binder thread queue, waiting for a thread to become available.</p><p>Why? I checked the main thread trace:</p><pre>T+100 - T+280: MainThread executing RecyclerView.onLayout() (180ms)<br>                └─ Inflating 15 complex ViewHolders<br>                └─ Measuring nested ConstraintLayouts</pre><p><strong>Root cause:</strong> The app was doing heavy UI work on the main thread. Meanwhile, the app’s limited Binder thread pool (typically 16 threads per process) was waiting to deliver the callback. Since all Binder threads were blocked waiting for the main thread’s looper, the speed update sat in the queue.</p><p>This is a <strong>classic automotive IPC problem</strong>: Android’s Binder threading model assumes callbacks can be processed asynchronously, but UI updates often need to run on the main thread — creating a dependency that introduces latency.</p><h3>Why Thread Pools Matter in Automotive</h3><p>Let me make this concrete with some numbers.</p><p><strong>Android’s Binder Thread Pool:</strong></p><ul><li>Each process gets a default pool of 16 Binder threads</li><li>These threads handle incoming IPC transactions (method calls, callbacks)</li><li>If all threads are busy, new transactions queue up</li><li>The kernel’s Binder driver manages this queue in /dev/binder</li></ul><p><strong>Automotive’s Challenge:</strong></p><ul><li>A typical instrument cluster might subscribe to 20–30 vehicle properties</li><li>High-frequency properties (RPM, speed, steering angle) update at 10–50 Hz</li><li>That’s 200–1500 callbacks per second across all properties</li><li>Each callback needs a Binder thread to deliver it</li></ul><p><strong>The Math:</strong></p><pre>16 Binder threads<br>÷ 30 concurrent property subscriptions<br>= ~0.5 threads per property on average<br>If each callback takes 10ms to process (UI update + Binder overhead):<br>Maximum sustainable rate = 1 / 0.01s = 100 Hz per thread<br>With 16 threads shared across properties: ~5 Hz per property max<br>But we&#39;re asking for 10-50 Hz updates!</pre><p>This is where priority inversion and thread starvation happen. A single slow callback (or main thread blockage) can cascade into delays across all vehicle properties.</p><h3>Solutions: Beyond “Move Work Off Main Thread”</h3><p>The quick fix was obvious: offload the heavy RecyclerView inflation to a background thread. But a staff-level solution requires understanding the systemic options.</p><h3>1. Rate Limiting (What We Did)</h3><pre>// Instead of SENSOR_RATE_FAST (50 Hz), use NORMAL (1-5 Hz) for non-critical properties<br>carPropertyManager.registerCallback(<br>    callback,<br>    VehiclePropertyIds.PERF_VEHICLE_SPEED,<br>    CarPropertyManager.SENSOR_RATE_NORMAL  // Reduced from FAST<br>)<br><br>// For truly critical properties, use FAST but ensure processing is lightweight<br>carPropertyManager.registerCallback(<br>    criticalCallback,<br>    VehiclePropertyIds.PERF_VEHICLE_SPEED,<br>    CarPropertyManager.SENSOR_RATE_FAST<br>)</pre><p><strong>Tradeoff:</strong> Lower update rates reduce IPC load but sacrifice real-time accuracy.</p><h3>2. Asynchronous APIs (The Modern Approach)</h3><p>Recent AOSP versions added getPropertyAsync() and setPropertyAsync() to avoid blocking the calling thread:</p><pre>// Old (blocking): Can starve Binder threads<br>val speed = carPropertyManager.getFloatProperty(<br>    VehiclePropertyIds.PERF_VEHICLE_SPEED, 0<br>)<br><br>// New (async): Returns immediately, callback invoked later<br>carPropertyManager.getPropertyAsync(<br>    VehiclePropertyIds.PERF_VEHICLE_SPEED, 0,<br>    executor, // Your own thread pool<br>    callback  // Invoked on executor thread<br>)</pre><p><strong>Benefit:</strong> You control the threading model and can prioritize critical properties.</p><h3>3. Shared Memory for High-Frequency Data</h3><p>For extremely high-frequency or large data (camera frames, LiDAR point clouds), Binder’s per-transaction overhead is prohibitive. AAOS supports shared memory via SharedMemory or LargeParcelable:</p><pre>// Instead of passing large arrays via Binder:<br>val sharedMem = SharedMemory.create(&quot;sensor_data&quot;, 1024 * 1024) // 1MB<br>// VHAL writes directly to shared memory<br>// App reads from shared memory without Binder copy</pre><p><strong>Benefit:</strong> Eliminates serialization overhead for large payloads.</p><h3>4. Dedicated Binder Threads for Critical Properties</h3><p>For safety-critical properties, you can create a dedicated process with its own Binder thread pool:</p><pre>&lt;!-- AndroidManifest.xml --&gt;<br>&lt;service<br>    android:name=&quot;.CriticalPropertyService&quot;<br>    android:process=&quot;:critical_properties&quot;<br>    android:isolatedProcess=&quot;false&quot;&gt;<br>    &lt;!-- This service gets its own 16 Binder threads --&gt;<br>&lt;/service&gt;</pre><p><strong>Benefit:</strong> Isolates critical data flow from UI-related IPC congestion.</p><h3>Key Takeaways: A Mental Model for AAOS IPC</h3><p>After this debugging journey, here’s the mental model I wish I’d had from the start:</p><h3>1. Think in Round-Trips, Not Layers</h3><p>Don’t just verify each component works:</p><ul><li>“Is the HAL publishing data?”</li><li>“Is CarService subscribed?”</li><li>“Is the app registered?”</li></ul><p>Instead, <strong>trace the full round-trip latency</strong>:</p><ul><li>Request path: App → CarService → VHAL (downward Binder calls)</li><li>Response path: VHAL → CarService → App (upward Binder callbacks)</li></ul><p>Use timestamps at each boundary to measure where delays occur.</p><h3>2. Binder Threads Are a Finite Resource</h3><p>Each process has a limited Binder thread pool. In automotive, with dozens of high-frequency subscriptions, <strong>you can saturate this pool</strong>. Monitor for these warning signs:</p><pre># Check Binder thread usage<br>adb shell cat /d/binder/stats | grep threads<br><br># Watch for &quot;waiting for binder&quot; in traces<br>adb shell perfetto ... | grep &quot;binder_wait&quot;</pre><h3>3. Cross-Domain IPC Has Extra Overhead</h3><p>The VHAL → CarService boundary crosses security domains:</p><ul><li>System domain (/dev/binder) ↔ Vendor domain (/dev/hwbinder or AIDL)</li><li>This requires SELinux policy checks and additional serialization</li></ul><p><strong>Implication:</strong> Don’t assume VHAL latency is just sensor read time — measure the Binder overhead separately.</p><h3>4. Callbacks + Main Thread = Latency Risk</h3><p>If your callback needs to update UI (common in automotive apps), you’re introducing a dependency:</p><pre>Binder thread delivers callback<br>    → Must post to main thread&#39;s Handler<br>        → Main thread processes callback<br>            → UI updates<br><br>If main thread is busy → entire chain stalls</pre><p><strong>Solution:</strong> Process callbacks on background threads and batch UI updates.</p><h3>Debugging Checklist for AAOS IPC Issues</h3><p>When you see stale or delayed vehicle property data:</p><p><strong>1. Verify the request path:</strong></p><pre># Did the app&#39;s registration reach CarService?<br>adb logcat -s CarService:V | grep registerListener<br><br># Did CarService subscribe to VHAL?<br>adb logcat -s VehicleHalImpl:V | grep subscribe</pre><p><strong>2. Verify the response path:</strong></p><pre># Is VHAL publishing updates?<br>adb logcat -s VehicleHalImpl:V | grep onPropertyEvent<br><br># Is CarService receiving them?<br>adb logcat -s CarService:V | grep onPropertyEvent<br><br># Is the app processing them?<br>adb logcat -s YourApp:V | grep onChangeEvent</pre><p><strong>3. Measure latency at each hop:</strong></p><pre>// In your callback<br>override fun onChangeEvent(value: CarPropertyValue&lt;*&gt;) {<br>    val receiveTime = SystemClock.elapsedRealtimeNanos()<br>    val halTime = value.timestamp // VHAL&#39;s timestamp<br>    val latency = (receiveTime - halTime) / 1_000_000 // ms<br>    <br>    if (latency &gt; 100) {<br>        Log.w(TAG, &quot;High latency: ${latency}ms for $value&quot;)<br>    }<br>}</pre><p><strong>4. Use Perfetto to visualize the full chain:</strong></p><pre># Capture Binder transactions + thread scheduling<br>adb shell perfetto \<br>  -c - --txt \<br>  -o /data/misc/perfetto-traces/automotive_trace \<br>  &lt;&lt;EOF<br>data_sources: {<br>    config {<br>        name: &quot;linux.ftrace&quot;<br>        ftrace_config {<br>            ftrace_events: &quot;binder/binder_transaction&quot;<br>            ftrace_events: &quot;binder/binder_transaction_received&quot;<br>            ftrace_events: &quot;sched/sched_switch&quot;<br>        }<br>    }<br>}<br>EOF</pre><p>Then load the trace in <a href="https://ui.perfetto.dev/">https://ui.perfetto.dev</a> and search for your property ID.</p><h3>Conclusion: The IPC Tax on Automotive Safety</h3><p>By the time I finished debugging, the speedometer was displaying correctly — but the lesson was bigger than one bug.</p><p>In Android Automotive, <strong>every real-time vehicle property pays an IPC tax</strong>: the latency cost of crossing multiple Binder boundaries to maintain Android’s security model. For non-safety-critical properties, this is acceptable. For safety-critical UIs, it requires careful design:</p><ul><li>Rate-limit non-critical properties</li><li>Use async APIs to avoid blocking</li><li>Monitor Binder thread pool usage</li><li>Consider shared memory for high-frequency data</li></ul><p>The frozen speedometer wasn’t a bug in the traditional sense — it was a <strong>collision between Android’s app-centric architecture and automotive’s real-time demands</strong>. Understanding this tension, and knowing how to trace IPC latency through the stack, is what separates platform engineers who debug symptoms from those who understand systems.</p><p>Next time you see a delayed gauge or stale sensor reading in an automotive UI, you’ll know where to start: follow the Binder trail, measure the round-trip, and check if the data is stuck in traffic.</p><h3>Resources</h3><p><strong>AOSP Source Code</strong></p><ul><li><a href="https://cs.android.com/android/platform/superproject/main/+/main:packages/services/Car/car-lib/src/android/car/hardware/property/CarPropertyManager.java">CarPropertyManager.java</a></li><li><a href="https://cs.android.com/android/platform/superproject/main/+/main:packages/services/Car/service/">CarService implementation</a></li><li><a href="https://source.android.com/docs/automotive/vhal/vhal-interface">Vehicle AIDL interface (VHAL)</a></li><li><a href="https://source.android.com/docs/core/architecture/ipc/binder-overview">Binder overview (AOSP)</a></li><li><a href="https://source.android.com/docs/core/architecture/ipc/binder-threading">Binder threading model</a></li></ul><p><strong>Debugging Tools</strong></p><ul><li><a href="https://perfetto.dev/docs/quickstart/android-tracing">Perfetto quickstart (Android)</a></li><li><a href="https://ui.perfetto.dev/">Perfetto UI</a></li></ul><p><strong>Related Reading</strong></p><p><em>In this series</em></p><ul><li><a href="https://medium.com/@rohithgd90/the-camera-that-launched-too-late-51717ac85c0d">Part 2: The Camera That Launched Too Late</a></li></ul><p><em>Android documentation</em></p><ul><li><a href="https://source.android.com/docs/core/architecture/hidl/binder-ipc">Binder IPC — use binder across security domains</a></li><li><a href="https://developer.android.com/training/cars">Android for Cars overview</a></li><li><a href="https://source.android.com/docs/automotive/guidelines">AAOS guidelines for development</a></li></ul><p><em>The frozen speedometer wasn’t a bug in the traditional sense — it was a collision between Android’s app-centric architecture and automotive’s real-time demands. Understanding this tension is what separates platform engineers who debug symptoms from those who understand systems.</em></p><p><em>But IPC latency is only half the story.</em></p><p><em>In Part 2, we shift into reverse — literally. The rear-view camera appears late. Binder is fine. The signal is correct. The intent is dispatched. The delay lives somewhere else entirely: inside the activity/task/window machine that Android uses to bring pixels to the screen. And in a vehicle, that delay has a name: an FMVSS 111 compliance failure.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0323df7d6234" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/the-speedometer-lied-debugging-real-time-ipc-in-android-automotive-0323df7d6234">The Speedometer Lied: Debugging Real-Time IPC in Android Automotive</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Day “Connected” Didn’t Mean “Rendering”]]></title>
            <link>https://proandroiddev.com/the-day-connected-didnt-mean-rendering-e0528d8d32e5?source=rss-3e5dc36b2b8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0528d8d32e5</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[unreal-engine]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[3d-rendering]]></category>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[Rohith Gaddam]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 22:54:43 GMT</pubDate>
            <atom:updated>2026-03-06T15:39:05.844Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why lifecycle policy and pixel flow matter more than view creation</strong></p><p>I had 47 lines of logs showing successful initialization. I had zero pixels on screen. The gap between those two facts cost us three days.</p><p>I was embedding a real-time 3D rendering engine into an Android UI. The surface was created. The service was connected. The camera state was applied. Every callback fired exactly when it should. No crashes. No errors. Just a perfectly blank screen and a stack of logs that insisted everything was fine.</p><p>That’s when it became clear: I was asking the wrong question.</p><h3>The Wrong Question</h3><p>For three days, I kept asking:</p><p><strong>“Is the view ready?”</strong></p><p>I checked creation callbacks. I verified lifecycle states. I added more logging to prove the TextureView existed, the surface was valid, and the engine had been notified. Every checkpoint came back green.</p><p>But the screen stayed blank.</p><h3>The Right Question</h3><p>What I should have been asking:</p><p><strong>“Are pixels actually arriving?”</strong></p><p>This distinction matters more than it sounds. On Android, a rendering surface is just a presentation target — a buffer where pixels can land. Android can allocate that buffer, manage its lifecycle, and composite whatever arrives. But Android cannot force an external rendering engine to start producing frames.</p><p>The engine and the platform have to shake hands, and that handshake has more steps than you’d think.</p><h3>Understanding the Contract</h3><p>When you integrate an external renderer (Unreal Engine, Unity, a custom OpenGL pipeline), the relationship looks like this:</p><pre>ANDROID SIDE:<br>1. Creates TextureView<br>2. Allocates SurfaceTexture when ready<br>3. Provides Surface handle to engine<br>4. Waits for frames to arrive<br>5. Composites received frames to screen<br><br>ENGINE SIDE:<br>1. Receives Surface handle<br>2. Binds rendering context to that surface<br>3. Initializes rendering pipeline<br>4. Starts producing frames<br>5. Pushes pixels to the surface buffer</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LTNF0BHRMFzG-yiplj50iw.png" /><figcaption>Android ↔ Engine Contract</figcaption></figure><p>Here’s the critical insight: <strong>a successful connection does not guarantee rendering has begun.</strong></p><p>Android completing steps 1–3 doesn’t mean the engine will complete steps 3–5. The engine might be waiting for resources to load. It might be stalled on a background thread. It might think the surface is invalid. Or — most insidiously — it might have started rendering to a <em>previous</em> surface that no longer exists.</p><p>I was measuring the handshake. I wasn’t measuring the pixel flow.</p><h3>What Healthy vs. Broken Actually Looks Like</h3><p>Once I started measuring frame arrival and content visibility, I saw two very different realities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7LvYj0fkNSJCIp8PZjy6rg.png" /><figcaption>Rendering timeline: healthy vs problem</figcaption></figure><p>The difference? In the broken case, the engine never started rendering — or started rendering to the wrong surface.</p><h3>The Lifecycle Multiplier</h3><p>Then came the second realization.</p><p>The blank screen didn’t happen consistently. It happened <em>after navigation</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_i869tcIVaTMILfJq_oc0A.png" /><figcaption>Lifecycle → Surface churn → blank window</figcaption></figure><p>When you navigate away from a Fragment containing a TextureView, Android destroys the view hierarchy. The TextureView is detached, and its surface becomes invalid. When you navigate back, a new TextureView is created with a new surface, and the engine must rebind.</p><p>If the engine doesn’t handle this rebinding correctly — or if there’s a race between surface destruction and engine notification — you end up rendering to a ghost surface. The engine thinks it’s rendering. Android has nothing to show.</p><p>Lifecycle policy, it turned out, dominated the user experience.</p><h3>A Pattern You Can Use Today</h3><p>What I needed was simple: measure reality, not assumptions.</p><p>Below is a small, safe pattern you can use in any Android app to answer:</p><ul><li>Did a surface get created?</li><li>Did frame updates start arriving?</li><li>Did meaningful pixels actually show up?</li><li>Am I churning surfaces due to lifecycle events?</li></ul><h3>1. A centralized monitor interface</h3><pre>interface RenderMonitor {<br>    fun onTextureViewCreated(feature: String, viewId: Int)<br>    fun onSurfaceAvailable(feature: String, surfaceId: Int, w: Int, h: Int)<br>    fun onReadySentToEngine(feature: String, surfaceId: Int)<br>    fun onFrameUpdate(feature: String, surfaceId: Int, updates: Long)<br>    fun onContentDetected(feature: String, surfaceId: Int, delayMs: Long)<br>    fun onSurfaceDestroyed(feature: String, surfaceId: Int)<br>}</pre><p>This interface is reusable across any feature that embeds external rendering.</p><h3>2. A simple log-based implementation</h3><pre>class LogRenderMonitor(private val tag: String = &quot;UE-Render&quot;) : RenderMonitor {<br>    private fun log(feature: String, msg: String) =<br>        android.util.Log.d(tag, &quot;[$feature] $msg&quot;)<br><br>    override fun onTextureViewCreated(feature: String, viewId: Int) =<br>        log(feature, &quot;TextureView created. viewId=$viewId&quot;)<br><br>    override fun onSurfaceAvailable(feature: String, surfaceId: Int, w: Int, h: Int) =<br>        log(feature, &quot;Surface available. surfaceId=$surfaceId size=${w}x$h&quot;)<br><br>    override fun onReadySentToEngine(feature: String, surfaceId: Int) =<br>        log(feature, &quot;onReady -&gt; engine notified. surfaceId=$surfaceId&quot;)<br><br>    override fun onFrameUpdate(feature: String, surfaceId: Int, updates: Long) =<br>        log(feature, &quot;Frame update. surfaceId=$surfaceId updates=$updates&quot;)<br><br>    override fun onContentDetected(feature: String, surfaceId: Int, delayMs: Long) =<br>        log(feature, &quot;CONTENT DETECTED. surfaceId=$surfaceId delayMs=$delayMs&quot;)<br><br>    override fun onSurfaceDestroyed(feature: String, surfaceId: Int) =<br>        log(feature, &quot;Surface destroyed. surfaceId=$surfaceId&quot;)<br>}</pre><p>Start with logging. Swap in your metrics pipeline later.</p><h3>3. The Compose wrapper (reusable across features)</h3><p><a href="https://gist.github.com/rohithgdm/23eb021adf9f0e01443bef2bc968e70e">https://gist.github.com/rohithgdm/23eb021adf9f0e01443bef2bc968e70e</a></p><p><strong>A note on the bitmap sampling:</strong> This runs on the main thread and allocates memory. The updates % 10L throttle keeps it lightweight, but for production you might throttle more aggressively or move sampling to a background thread using PixelCopy.request() when you have window access. The key idea is sampling occasionally—not every frame.</p><p><strong>📝 Note on Production Usage</strong></p><p>The bitmap sampling approach shown here is intentionally simple for educational purposes. In production systems, consider:</p><ul><li>Using PixelCopy.request() with a background thread when you have Window access</li><li>Implementing more aggressive throttling (every 30–50 frames instead of 10)</li><li>Adding timeout detection (if no content after N seconds, trigger fallback)</li><li>Integrating with your existing observability pipeline (DataDog, Firebase, custom metrics)</li></ul><h3>What This Gives You</h3><p>With this pattern in place, you can conclusively answer:</p><p>✓ Was the surface created?<br> ✓ Did frame updates start (updates &gt; 0)?<br> ✓ How long until the first meaningful pixel appeared?<br> ✓ Are we recreating surfaces frequently due to lifecycle churn?</p><p>It turns opinions into measurable facts. When someone says “the engine is working fine,” you can reply with: “The engine was notified 800ms ago and I’ve received zero frame updates.”</p><p>That’s a different conversation.</p><h3>References &amp; Further Reading</h3><p><strong>Android Framework Documentation:</strong></p><ul><li><a href="https://developer.android.com/reference/android/view/TextureView">TextureView</a> — Official Android documentation on TextureView and surface lifecycle</li><li><a href="https://source.android.com/docs/core/graphics">Graphics Architecture</a> — Deep dive into Android’s graphics pipeline and BufferQueue mechanism</li><li><a href="https://developer.android.com/jetpack/compose/migrate/interoperability-apis/views-in-compose">AndroidView in Compose</a></li></ul><p><strong>External Rendering Integration:</strong></p><ul><li><a href="https://docs.unrealengine.com/5.0/en-US/android-development-for-unreal-engine/">Unreal Engine Android Development</a> — Epic Games official documentation</li><li><a href="https://source.android.com/docs/core/graphics/arch-bq-gralloc">Graphics Architecture — BufferQueue</a> — Understanding Android’s producer-consumer rendering model</li></ul><p><strong>Related Articles:</strong></p><ul><li><a href="https://medium.com/proandroiddev/the-speedometer-lied-debugging-real-time-ipc-in-android-automotive-0323df7d6234">The Speedometer Lied: Debugging Real-Time IPC in Android Automotive</a> — Deep dive into Binder IPC performance debugging in AAOS</li></ul><h3>The Takeaway</h3><p>“Connected” does not mean “rendering.” Android can present pixels, but it cannot create them. The contract between platform and engine is more fragile than most APIs I work with daily, and lifecycle policy can dominate the entire user experience.</p><p>A small amount of observability prevents weeks of blame and guesswork.</p><p>The next time you see a blank screen with healthy logs, resist the urge to add more logging to the handshake. Instead, measure the pixel flow. The answer might surprise you — and it will definitely save you time.</p><p><em>Have you hit this issue? What did you end up measuring? I’d love to hear your war stories in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0528d8d32e5" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/the-day-connected-didnt-mean-rendering-e0528d8d32e5">The Day “Connected” Didn’t Mean “Rendering”</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>