<?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 Neeraj Sahu on Medium]]></title>
        <description><![CDATA[Stories by Neeraj Sahu on Medium]]></description>
        <link>https://medium.com/@neerajsahu14?source=rss-6b54cc9d8a02------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Neeraj Sahu on Medium</title>
            <link>https://medium.com/@neerajsahu14?source=rss-6b54cc9d8a02------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 07:49:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@neerajsahu14/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[Building an AOSP System App with Gradle, Without Breaking the Platform Build]]></title>
            <link>https://medium.com/@neerajsahu14/building-an-aosp-system-app-with-gradle-without-breaking-the-platform-build-0deecc5aeba5?source=rss-6b54cc9d8a02------2</link>
            <guid isPermaLink="false">https://medium.com/p/0deecc5aeba5</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[aosp]]></category>
            <dc:creator><![CDATA[Neeraj Sahu]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 02:12:59 GMT</pubDate>
            <atom:updated>2026-10-04T02:42:52.035Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>How I got a privileged platform app that uses hidden APIs, a JNI library and the platform signing key to build in Android Studio, while </em><em>m kept working exactly as before.</em></blockquote><p>If you’ve worked on an Android platform app that lives inside an AOSP tree, you know how it goes. Every change means m MyApp, waiting for Soong to finish thinking, pushing the APK, rebooting, and repeating. Android Studio doesn&#39;t help much either: the project won&#39;t open as-is, so you get no code navigation, no autocomplete for @hide APIs, and no quick incremental builds.</p><p>I recently worked on a system app like that. It’s a privileged app in /system/priv-app that runs as android.uid.system and depends on:</p><ul><li>hidden framework APIs (@hide, com.android.internal.*, and some vendor-specific framework classes),</li><li>libcore internals (core-oj, core-libart),</li><li>a small JNI library written in C++,</li><li>another Java library built from a sibling project in the AOSP tree,</li><li>a slice of SettingsLib,</li><li>AIDL interfaces kept in a git submodule,</li><li>and the platform certificate, because it runs with the system UID.</li></ul><p>My goal was to build it with Gradle (Kotlin DSL) and open it in Android Studio. There was one hard rule: the Soong build could not change. ROM and OTA builds would keep using Android.bp, and Gradle was only there to make day-to-day development faster.</p><p>This post covers how I set it up and the problems I hit along the way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXAYADRUYr9z_02Dr0_K5g.png" /></figure><h3>The approach: two build systems, one set of sources</h3><p>The first thing I decided was to leave the source files where they were. Nothing in src/, res/, assets/ or AndroidManifest.xml moved. The Gradle app/ module holds only a build script and points at the existing directories:</p><pre>sourceSets {<br>    getByName(&quot;main&quot;) {<br>        manifest.srcFile(rootProject.file(&quot;AndroidManifest.xml&quot;))<br>        java.srcDirs(rootProject.file(&quot;src&quot;), rootProject.file(&quot;aidl-submodule/src&quot;))<br>        kotlin.srcDirs(rootProject.file(&quot;src&quot;), rootProject.file(&quot;aidl-submodule/src&quot;))<br>        aidl.srcDirs(rootProject.file(&quot;aidl-submodule/aidl&quot;))<br>        res.srcDirs(rootProject.file(&quot;res&quot;))<br>        assets.srcDirs(rootProject.file(&quot;assets&quot;))<br>    }<br>}</pre><p>That way a new Java file, resource or manifest entry goes into both builds automatically, and the two builds have no copies of the code that could drift apart.</p><p>The final layout:</p><pre>MySystemApp/<br>├── Android.bp              Soong (unchanged, apart from one exclude)<br>├── AndroidManifest.xml     shared<br>├── src/ res/ assets/       shared<br>├── aidl-submodule/         shared<br>├── jni/<br>│   ├── Android.bp          Soong native lib<br>│   ├── CMakeLists.txt      Gradle native lib (new)<br>│   └── native.cpp          shared<br>├── libs/<br>│   ├── platform/           framework.jar, core-oj.jar, core-libart.jar (new)<br>│   └── VERSION.txt         where each jar came from (new)<br>├── settings.gradle.kts<br>├── build.gradle.kts<br>├── gradle.properties<br>├── app/build.gradle.kts    build script only, no sources<br>├── settingslib/            minimal SettingsLib subset<br>└── build.sh                refresh libs, build, deploy</pre><h3>Problem 1: Hidden APIs don’t exist in the SDK</h3><p>In Soong, platform_apis: true compiles your app against the real framework, hidden members included. With Gradle you get the public SDK android.jar, so anything marked @hide fails with cannot find symbol.</p><p>Adding framework.jar as a compileOnly dependency is not enough. It works for classes that are entirely hidden, but not for hidden members of public classes, such as UserHandle.myUserId() or JSONObject.keySet(). javac finds android.os.UserHandle in android.jar first, and that copy doesn&#39;t have the hidden method.</p><p>The fix is to put the platform jars ahead of android.jar on the boot classpath, so the platform&#39;s copy of each class wins. You used to do this with -Xbootclasspath/p, but that flag was removed in JDK 9. What works is setting bootstrapClasspath on every JavaCompile task:</p><pre>// root build.gradle.kts<br>val platformJars = listOf(&quot;framework.jar&quot;, &quot;core-libart.jar&quot;, &quot;core-oj.jar&quot;)<br>    .map { file(&quot;libs/platform&quot;).resolve(it) }<br>extra[&quot;platformJars&quot;] = platformJars</pre><pre>subprojects {<br>    tasks.withType&lt;JavaCompile&gt;().configureEach {<br>        inputs.files(platformJars).withPropertyName(&quot;platformJars&quot;)<br>        doFirst {<br>            val missing = platformJars.filterNot { it.exists() }<br>            check(missing.isEmpty()) {<br>                &quot;Platform jars missing (run ./build.sh):\n&quot; + missing.joinToString(&quot;\n&quot;)<br>            }<br>            options.bootstrapClasspath =<br>                files(platformJars) + (options.bootstrapClasspath ?: files())<br>        }<br>    }<br>}</pre><p>The app module also adds them as compileOnly, because Kotlin needs them too and because they must not be packaged into the APK (the device already has them):</p><pre>dependencies {<br>    compileOnly(files(platformJars))<br>}</pre><h3>The catch: this only works with Java 8 source/target</h3><p>This took me a while to figure out. If sourceCompatibility is 9 or higher, AGP compiles against a --system image and ignores the boot classpath entirely, so all your hidden-API errors come back. The project has to stay at:</p><pre>compileOptions {<br>    sourceCompatibility = JavaVersion.VERSION_1_8<br>    targetCompatibility = JavaVersion.VERSION_1_8<br>}<br>kotlinOptions { jvmTarget = &quot;1.8&quot; }</pre><p>You still run Gradle on JDK 17, which AGP 8.x requires. Only the <em>language level</em> stays at 8. I left a comment in the build file explaining why, so nobody “upgrades” it later.</p><h3>Problem 2: Where do the platform jars come from?</h3><p>framework.jar and the libcore jars only exist inside an AOSP out/ directory after a build. I didn&#39;t want every developer to need a full platform build just to open the project, so I committed them to libs/platform/.</p><p>That raises the question of which jars to commit. The full framework.jar class jar is about 38 MB. Soong also produces turbine header jars: every class and member, @hide ones included, but no method bodies. That&#39;s all compileOnly needs, and framework.jar drops to about 13 MB.</p><pre>out/soong/.intermediates/frameworks/base/framework/android_common/turbine-combined/framework.jar<br>out/soong/.intermediates/libcore/core-oj/android_common/turbine-combined/core-oj.jar<br>out/soong/.intermediates/libcore/core-libart/android_common_apex31/turbine-combined/core-libart.jar</pre><p>The app also statically links a Java library built from a sibling project in the tree. Its Soong javac output jar goes into libs/ the same way, but as an implementation dependency since it gets bundled.</p><p>Committed binaries go stale, so I wrote a build.sh that:</p><ol><li>runs source build/envsetup.sh &amp;&amp; lunch &lt;target&gt;,</li><li>runs m on only those four Soong outputs, not the whole ROM,</li><li>copies them into libs/,</li><li>writes libs/VERSION.txt with the lunch target, source project, git revision and sha256 of each jar,</li><li>git adds libs/,</li><li>runs ./gradlew assembleRelease.</li></ol><pre># Generated by build.sh - do not edit.<br># jar | source project | git revision | sha256<br>lunch: &lt;product&gt;-userdebug<br>platform/framework.jar   | frameworks/base | c365db88 | 4a7b2e...<br>platform/core-libart.jar | libcore         | a151d37  | d44c39...<br>platform/core-oj.jar     | libcore         | a151d37  | 17a99f...<br>SiblingLib.jar           | vendor/.../SiblingLib | bd04dc7 | b33d77...</pre><p>VERSION.txt makes it easy to see in a PR diff which framework revision the build compiles against.</p><p>One thing about shell scripts: envsetup.sh and lunch weren&#39;t written for set -euo pipefail. Commands inside them are <em>expected</em> to fail (a harmless fatal: not a git repository at the tree root, for example), and under strict mode that silently kills your script. I turn strict mode off in the subshell that sources them and check the results myself:</p><pre>(<br>    cd &quot;$AOSP_ROOT&quot;<br>    set +euo pipefail<br>    source build/envsetup.sh &gt;/dev/null 2&gt;&amp;1<br>    type lunch &gt;/dev/null 2&gt;&amp;1 || die &quot;sourcing build/envsetup.sh failed&quot;<br>    lunch &quot;$LUNCH_TARGET&quot;      || die &quot;lunch $LUNCH_TARGET failed&quot;<br>    m &quot;${targets[@]}&quot;          || die &quot;AOSP build failed&quot;<br>)</pre><h3>Problem 3: Mapping every Android.bp dependency</h3><p>Next I went through Android.bp line by line and found a Gradle equivalent for each entry:</p><ul><li>platform_apis: true → platform jars on the boot classpath (compile only)</li><li>libs: [&quot;core-oj&quot;] + libcore → core-oj.jar, core-libart.jar (compile only)</li><li>libs: [&quot;bouncycastle-unbundled&quot;] → nothing extra: com.android.internal.org.bouncycastle.* is already inside framework.jar</li><li>static_libs: [&quot;SiblingLib&quot;] → the committed jar from build.sh (bundled)</li><li>java_import prebuilts → implementation(files(...)) (bundled)</li><li>static_libs: [&quot;androidx.core_core&quot;] → androidx.core:core from Maven</li><li>static_libs: [&quot;SettingsLib&quot;] → a small :settingslib module (more below), plus androidx.appcompat, which SettingsLib had been pulling in transitively. The manifest uses Theme.AppCompat, so it has to be declared explicitly in Gradle.</li><li>jni_libs → externalNativeBuild { cmake }</li><li>aidl.include_dirs → sourceSets.main.aidl.srcDirs(...)</li><li>certificate: &quot;platform&quot; → a signingConfig (Problem 5)</li></ul><h3>SettingsLib: take only what you need</h3><p>The real SettingsLib is huge and full of platform dependencies. The app used exactly one class (DisplayDensityUtils), one static helper, and a few strings. So the :settingslib Gradle module is a tiny library module with just those files copied in and the same package name. Soong keeps linking the real SettingsLib. If the app ever uses more SettingsLib classes, you copy them in.</p><h3>Problem 4: The native library</h3><p>Soong builds the JNI library from jni/Android.bp. For Gradle I added a CMakeLists.txt next to it that uses the same source file and the same flags:</p><pre>cmake_minimum_required(VERSION 3.22.1)<br>project(native_lib CXX)</pre><pre>add_library(native_lib SHARED native.cpp)<br>target_compile_options(native_lib PRIVATE -Wall -Wextra -O2 -fvisibility=hidden)<br>target_link_libraries(native_lib log)</pre><p>To match Soong’s packaging:</p><pre>defaultConfig {<br>    ndk { abiFilters += &quot;arm64-v8a&quot; }          // Soong embeds the primary arch only<br>    externalNativeBuild {<br>        cmake { arguments += &quot;-DANDROID_STL=c++_static&quot; }<br>    }<br>}<br>packaging {<br>    jniLibs { useLegacyPackaging = false }     // = use_embedded_native_libs: stored uncompressed<br>}</pre><p>useLegacyPackaging = false matters. Soong&#39;s use_embedded_native_libs: true stores the .so uncompressed inside the APK and loads it from there, so nothing gets extracted to /data. That&#39;s the behavior you want for a system app.</p><p>Since the manifest’s minSdk is 19 and arm64 starts at API 21, the NDK complains. android.ndk.suppressMinSdkVersionError=21 in gradle.properties handles it.</p><h3>Problem 5: Signing with the platform key</h3><p>An app with android:sharedUserId=&quot;android.uid.system&quot; must be signed with the same platform key as the ROM. Otherwise the package manager rejects it at boot and the app just disappears.</p><p>I set up two signing sources:</p><ol><li>The CI keystore, if a password is provided through ~/.gradle/gradle.properties, an uncommitted keystore.properties, or an environment variable. This matches the keys on production-signed devices.</li><li>Fallback: the AOSP platform key from the tree. A small Gradle task converts build/target/product/security/platform.pk8 + platform.x509.pem into a PKCS12 keystore under build/:</li></ol><pre>val generatePlatformKeystore by tasks.registering {<br>    val pk8 = aospRoot.resolve(&quot;build/target/product/security/platform.pk8&quot;)<br>    val pem = aospRoot.resolve(&quot;build/target/product/security/platform.x509.pem&quot;)<br>    inputs.files(pk8, pem)<br>    outputs.file(platformKeystore)<br>    doLast {<br>        val tmpKey = File(temporaryDir, &quot;platform.key.pem&quot;)<br>        run(&quot;openssl&quot;, &quot;pkcs8&quot;, &quot;-inform&quot;, &quot;DER&quot;, &quot;-nocrypt&quot;,<br>            &quot;-in&quot;, pk8.path, &quot;-out&quot;, tmpKey.path)<br>        run(&quot;openssl&quot;, &quot;pkcs12&quot;, &quot;-export&quot;, &quot;-in&quot;, pem.path, &quot;-inkey&quot;, tmpKey.path,<br>            &quot;-name&quot;, &quot;platform&quot;, &quot;-passout&quot;, &quot;pass:android&quot;, &quot;-out&quot;, platformKeystore.path)<br>        tmpKey.delete()<br>    }<br>}</pre><pre>tasks.matching { it.name.startsWith(&quot;validateSigning&quot;) }.configureEach {<br>    dependsOn(generatePlatformKeystore)<br>}</pre><p>Because the key is converted at build time, it’s never committed. It’s also the only thing the Gradle build still reads from the AOSP tree.</p><h3>Problem 6: You can’t adb install a system app</h3><p>Android Studio’s Run button, ./gradlew installDebug and adb install all fail for a privileged system-UID app. You have to replace the APK in /system/priv-app and reboot, and it&#39;s easy to get that wrong. So build.sh --deploy does it step by step:</p><ol><li>adb root, with a clear error if the device runs a user ROM.</li><li>Checks the app actually exists at /system/priv-app/&lt;App&gt;/&lt;App&gt;.apk.</li><li>Backs up the device’s current APK to build/deploy/.</li><li>adb remount. On a verity-enabled device the first remount disables verity and needs a reboot, so the script reboots, waits for sys.boot_completed, runs adb root and remounts again.</li><li>If an old adb install left an update in /data/app, it removes it with pm uninstall-system-updates, since that copy would shadow the system APK.</li><li>adb push, chown root:root, chmod 644, restorecon, removes the stale oat/, sync.</li><li>Reboots, then verifies pm path &lt;package&gt; points at the pushed APK.</li></ol><pre>./build.sh                      # refresh libs from AOSP, then build<br>./build.sh --gradle-only -d     # build with committed libs, deploy to device<br>./build.sh --deploy-only        # push the last built APK</pre><h3>Keeping Soong happy</h3><p>The whole setup falls apart if m breaks, so I made sure the two build systems stay out of each other&#39;s way.</p><p>Source globs. Android.bp used srcs: [&quot;**/*.java&quot;, &quot;**/*.kt&quot;, &quot;**/*.aidl&quot;], so Soong would pick up the Java in settingslib/ (duplicate classes!) and the generated sources under app/build/. This was the only change to Android.bp:</p><pre>exclude_srcs: [<br>    &quot;app/**/*&quot;,<br>    &quot;settingslib/**/*&quot;,<br>    &quot;build/**/*&quot;,<br>    &quot;.gradle/**/*&quot;,<br>],</pre><p>The rest:</p><ul><li>Soong ignores *.gradle.kts, gradlew, CMakeLists.txt and build.sh.</li><li>Soong never uses libs/platform/ or the committed sibling jar. It still builds framework, libcore and the sibling library from source, so a ROM can never pick up a stale jar.</li><li>Gradle never writes into out/. build.sh only reads it.</li><li>.gradle/, build/, .cxx/, local.properties, keystore.properties and *.iml are git-ignored.</li></ul><p>After the conversion I ran m MyApp again and confirmed the APK still installed to system/priv-app/... with the native library embedded.</p><h3>The two APKs are equivalent, not identical</h3><p>It’s worth writing down where they differ, so nobody is surprised later:</p><ul><li>Shrinking: Soong runs R8 in shrink-only mode. I left isMinifyEnabled = false in Gradle so nothing reached only through reflection gets stripped. The Gradle APK is larger as a result.</li><li>SettingsLib: full library vs. a minimal subset.</li><li>versionCode: Soong stamps platform apps without a versionCode with PLATFORM_SDK_VERSION, so I hardcoded the same value in Gradle.</li><li>Native toolchain: platform clang vs. NDK clang.</li><li>Sibling library: built from current source vs. the committed jar snapshot.</li></ul><p>Release builds for ROMs and OTAs still come from Soong. The Gradle APK is for development and testing.</p><h3>Lessons learned</h3><ol><li>Don’t move sources. Point Gradle at the existing layout. Two builds over one source tree is much easier to maintain than two copies.</li><li>compileOnly isn&#39;t enough for hidden APIs. Hidden <em>members of public classes</em> need the platform jars on the boot classpath, and that only works at Java 8 source/target.</li><li>Use turbine header jars. They have everything javac needs at about a third of the size.</li><li>Commit generated jars, and record where they came from. A VERSION.txt with revisions and hashes makes staleness easy to spot in review.</li><li>Look for transitive dependencies. SettingsLib had been quietly providing AppCompat. In Gradle, every dependency Soong pulled in transitively has to be declared.</li><li>Automate the deploy, and check the signing cert before you push. Getting the system-app deploy wrong costs you a reboot cycle, or a missing app.</li><li>Write down how to keep the builds in sync. New prebuilt jar? Update both files. Changed a native flag? Update both files. A table in the README covering this is worth having.</li></ol><p>The result: the app opens in Android Studio with full navigation and autocomplete for hidden APIs, one command deploys to a device, and the platform build works exactly as it did before.</p><p><em>If you’re doing something similar with your own platform app, I’d like to hear how you handled the hidden-API classpath. Let me know in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0deecc5aeba5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>