Embed in an Android app
Build BakeNative for Android, show a bundle in an existing Android app, and ship updates.
On Android, a BakeNative screen is BakeNativeView, an Android ViewGroup. You put it in an Activity, a Fragment, or Compose through AndroidView, and the rest of your app stays native.
The Android host is a Kotlin library, :bakenative, with the Rust core in libbakenative.so. This guide builds the library from a BakeNative checkout. To add the runtime as one Maven dependency instead (one libbakenative.so per ABI, Hermes linked in), see Ship as an Android AAR.
Requirements
| macOS | Builds Android Hermes. tools/build-hermes/android.sh runs only on macOS |
| JDK 17 or newer | Runs Gradle |
Android SDK with platform 37, NDK 28.2.13676358 and CMake 3.22.1 | sdkmanager "platforms;android-37" "ndk;28.2.13676358" "cmake;3.22.1" |
Rust with the aarch64-linux-android target and cargo-ndk | Builds libbakenative.so: rustup target add aarch64-linux-android, cargo install cargo-ndk |
| Node 22.22.2+ and pnpm 10 | Runs the bake CLI |
| An arm64 device or emulator with Android 10 (API 29) or newer | The libraries are built for arm64-v8a by default (BAKE_ANDROID_ABIS=arm64-v8a,x86_64 adds x86_64 emulators). On a Mac, use an Apple Silicon emulator |
bake build --target android and the Gradle build also run on Windows. Android Hermes needs the Mac, and libbakenative.so is built there with it.
Build the toolchain
Clone and install
git clone https://github.com/gronxb/bake-native.git bakenative
cd bakenative
pnpm installBuild Hermes
pnpm hermesOn macOS, this builds Apple Hermes first. That build gives bake build its hermesc. It then builds Android Hermes and writes libhermesvm.so and libbakehermes.so to native/hermes/artifacts/android/arm64-v8a (and x86_64). Android Hermes is built without Intl.
Without the NDK, it skips Android and says so. pnpm hermes -- --android rebuilds only Android. The script looks for the SDK in ANDROID_HOME (default ~/Library/Android/sdk) and for the NDK in ANDROID_NDK_ROOT.
Check it works
Start an emulator or connect a phone, then run:
pnpm androidThis builds the example app (examples/app) for Android, builds libbakenative.so, builds the example host (examples/android), installs it and launches it: an Activity with a native Toolbar and an BakeNativeView below it. With more than one device, pass pnpm android -- --serial <serial>. pnpm android -- --no-run only builds.
Build a bundle
In your BakeNative app (see Installation for adding the CLI):
pnpm bake build --target android --bakeThis writes dist/android:
| File | Content |
|---|---|
app.js | The JavaScript that app.hbc was compiled from. The app does not need it at run time |
app.hbc | Hermes bytecode |
app.baked | First-screen snapshot (--bake) |
app.css | Styles |
manifest.json | Host protocol, renderer batch digest and a SHA-256 per file |
assets/ | Images, when the app has any |
The first bake build in a checkout compiles the native tools (bake-css-lint, bake-frame) with Cargo. It prints nothing while it does, and it takes a few minutes.
bake build fails when your code uses Intl or passes locales to toLocaleString, toLocaleDateString, toLocaleTimeString or localeCompare, because Android Hermes is built without Intl. typeof Intl checks are allowed.
Embed in an Android app
Build the core
:bakenative takes libbakenative.so and the stripped Hermes libraries from its build/rustJniLibs directory. Build them once, and again after you update the checkout:
cd bakenative
BAKE_HERMES_ARTIFACTS=$PWD/native/hermes/artifacts native/android/bakenative/build-rust.shThe script needs ANDROID_NDK_ROOT. pnpm android runs it for you.
Add the library
Include the library modules from your BakeNative checkout in your app's settings.gradle.kts. The paths point at the checkout:
dependencyResolutionManagement {
versionCatalogs {
// The library modules' build scripts use this catalog.
create("libs") { from(files("../bakenative/native/android/gradle/libs.versions.toml")) }
}
}
include(":bakenative")
project(":bakenative").projectDir = file("../bakenative/native/android/bakenative")
include(":controls")
project(":controls").projectDir = file("../bakenative/native/android/controls"):controls draws form controls, <dialog> sheets and text fields with Material 3 Compose and EditText. If your app already has a libs catalog, add the catalog's android-library and kotlin-compose plugins and its Compose libraries to yours instead. The modules use Android Gradle Plugin 9 (9.4.1) and its built-in Kotlin.
Then, in your app's build.gradle.kts:
android {
defaultConfig {
minSdk = 29
ndk { abiFilters += "arm64-v8a" }
}
// dist/android of your BakeNative app, copied into the APK as assets/bakenative/app/.
sourceSets.getByName("main").assets.directories += "src/main/bakenative-assets"
packaging {
jniLibs.useLegacyPackaging = false // load the libraries from the APK, uncompressed
}
}
dependencies {
implementation(project(":bakenative"))
implementation("androidx.activity:activity-compose:1.13.0")
}Copy app.hbc, every baked .baked, app.css and manifest.json (and assets/ and fonts/, if present) from dist/android to src/main/bakenative-assets/bakenative/app/. examples/android/app/build.gradle.kts does this with a Gradle Sync task, copyBakeNativeBundle, before every build.
Show the view
Create the view in a ComponentActivity and load the bundle:
import android.os.Bundle
import androidx.activity.ComponentActivity
import dev.bakenative.BakeNativePrewarm
import dev.bakenative.BakeNativeBundle
import dev.bakenative.BakeNativeView
class CheckoutActivity : ComponentActivity() {
private val bundle = BakeNativeBundle.Asset("bakenative/app")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
BakeNativePrewarm.prewarm(this, bundle) // optional: prepares the first screen on a worker
val view = BakeNativeView(this)
setContentView(view)
view.load(bundle)
}
}In a Fragment, return the view from onCreateView. In Compose, wrap it in AndroidView:
AndroidView(
factory = { ctx -> BakeNativeView(ctx).apply { load(BakeNativeBundle.Asset("bakenative/app")) } },
modifier = Modifier.fillMaxSize(),
)Declare the configuration changes the view follows itself, so the Activity is not recreated and the screen does not reload:
<activity
android:name=".CheckoutActivity"
android:configChanges="uiMode|fontScale|orientation|screenSize|screenLayout|smallestScreenSize|density|keyboardHidden|keyboard"
android:windowSoftInputMode="adjustResize" />-
The host Activity. Use a
ComponentActivity, or another Activity that provides aViewTreeLifecycleOwner. The controls in:controlsare Compose. -
The first frame. With a baked
.baked, the view lays the snapshot out at its first measure and creates its views before the first draw, while Hermes loads the bundle. JavaScript then takes over the same views. Without a snapshot, the first frame waits for JavaScript, and later launches use a first screen the view cached on the device (cachesFrames, on by default). -
The bundle files.
BakeNativeBundle.Assetcopies the bundle out of the APK once per app version, into the app's files directory.BakeNativeBundle.Directory(dir)opens a folder on disk. For bundles withlocales, both open the frame named for the app's locale in the manifest. -
Lifetime. Detaching the view closes its root. A view loads once: to show another bundle, create a new view.
-
The thread. Create the view and call
loadon the main thread. The core runs JavaScript on its own thread, and the main thread never waits for it. -
Size, insets, dark mode and font scale. The view lays the snapshot out at its real size, with the system bars it sits under as safe insets. It follows dark mode, font scale, rotation and the keyboard.
-
Hydration.
view.hydrationpicks when JavaScript takes over the snapshot (IDLE, the default, after the first frame). See Choosing when to hydrate. -
Events.
view.listener(anBakeNativeView.Listener) reports the first screen, the first frame, launch phases, prewarm outcomes and diagnostics. -
One section of a native screen.
view.fitsContent = true(beforeload) makes the view as tall as its page inside aScrollView(contentHeight,onContentHeight); it does not scroll on its own and leaves the system bars to the screen. The page is laid out at a 1 px viewport height:vhunits,position: fixedand virtual lists do not apply.
examples/android is a complete host: a native toolbar with a dark mode action, the view below it, and the prewarm flow. native/android/bakenative/README.md describes how the host works.
Prepare a screen before it opens
If your app opens the BakeNative screen later, it can prepare the first screen earlier, for example when the button that opens it appears:
val cancel = BakeNativePrewarm.prewarm(context, bundle)
cancel() // only if the screen will not open after allprewarm returns at once. On background threads it warms the process up (once), copies the bundle, loads libbakenative.so, and reads and lays out the snapshot. It does not start Hermes. Call it once per bundle; for several, bundles.map { BakeNativePrewarm.prewarm(context, it) }.
The view takes the prepared result when it loads the same bundle. The prewarm uses the size, scheme and insets a view of this bundle last opened with, kept across launches, else the Activity's window. A frame laid out for another size is never shown.
The result is released on its own: when a view takes it, when a newer prewarm of the bundle replaces it, on onTrimMemory, when the bundle files change on disk, and after a minute unused. cancel() releases it now, only if it is still the one that call prepared; dropping the returned value keeps it. examples/android shows this with pnpm android -- --open-later.
Native modules
Android modules implement the Kotlin contract generated from the module's spec (native/<name>/<Name>.native.ts): an abstract class, <Name>Spec, in the generated Gradle module. bake native new writes the spec, a Kotlin implementation and a JVM test:
bake native new Clipboard --platform android --target com.example.appclass ClipboardModule(private val context: Context) : ClipboardSpec() {
// Promise<void> in the spec: a suspend fun, called on a background thread.
override suspend fun writeText(text: String) = withContext(Dispatchers.Main) {
context.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("", text))
}
}Register the app's modules on the view before load(): view.modules.registerAll(BakeNativeBundleModules.root(clipboard = ClipboardModule(this))) (a module the bundle calls unguarded is a required parameter). view.modules starts with Platform, whose os is "android". The spec gives the same TypeScript on every host; bake native types writes it.
The full guide, with the type mapping and threads, is Native modules.
Ship updates
A bundle is a plain folder, so you can replace it without a new app release. Ship the whole dist/android folder every time. The files belong together: see Shipping updates.
Load a downloaded bundle
Write the download to a new folder, then load it with BakeNativeBundle.Directory:
val view = BakeNativeView(this)
setContentView(view)
try {
view.load(BakeNativeBundle.Directory(File(filesDir, "updates/42")))
} catch (e: IllegalStateException) {
Log.w(TAG, "skipping update: ${e.message}")
// fall back to the bundle in the APK, in a new view
}The Rust core checks the bundle before anything is drawn. A bundle that this app cannot run fails closed: the view does not open, and load throws IllegalStateException with the reason, such as bake_root_open failed (-6): incompatible bundle: bundle host protocol 99 > supported 3. A bundle is refused when its manifest.json is missing or not JSON, when it was built for a newer host protocol, or when it was built by a bake from another BakeNative version (another renderer batch stream). Rebuild it with the bake that matches the app. When the view has a cached first screen of the bundle, it opens at its first measure, so the error comes from that layout pass instead of load.
To show a new bundle, create a new view with the new folder. Do not overwrite the files of a bundle that a view is running. The view never adopts a snapshot that was baked from a different app.hbc: if the files get mixed up, JavaScript renders the screen again from scratch.
Compatibility: requires and provides
A downloaded bundle runs when the app has what it uses. bake build writes requires into manifest.json: the renderer ops, events and CSS properties the bundle uses, and the native members it calls. The bundle runs when the app provides each of them with the same shape (requires ⊆ provides). A newer app that adds ops, events, properties or members keeps running older bundles. A bundle that needs something the app removed or changed is refused, with the missing item named. On Android, dev.bakenative.BakeNativePackage (fromAssets, check, use) runs this check (the Rust core's bake_bundle_check) before you open a downloaded bundle, and bake release check gives the same answer in CI. See Packaging: Android for the planned package format.
Not yet
- A Maven package on a server. The runtime AAR is built and published to a local repository (Android AAR); otherwise your app builds
:bakenativeand:controlsfrom the checkout. - Building Android Hermes on Windows or Linux.
- Jetpack Compose components (
@bake-native/octane/ui/jetpack-compose). - A view loads once. Detaching it closes the root, and it cannot load again.
- Fields inside an open
<dialog>live in the sheet's own window. The page's keyboard inset andKeyevents do not cover them. textareaignoresenterkeyhint: Enter inserts a newline.- The large header title is a taller Material bar, not a collapsing one.
- A translucent box (
opacitybelow 1) clips children that overflow it.
See also
- Embed in a Windows app: the same steps for the Windows host.
- Native UI and Universal UI: components that draw on Android too; Jetpack Compose for Android-only ones.