# Guide: building an Android APK for a mithril-lynx app from scratch, on the command line

> **Status**: ported from the previous mithril-lynx, which this guide
> predates. Parts B (Android host), C (wiring the bundle in), and D (the
> font-prefetch hack) are framework-agnostic — they only care that
> `dist/main-thread.bundle` exists, never how it was produced — and are
> unchanged and still accurate, including the `create-mithril-lynx`
> command lines (that CLI already generates the current architecture).
> **Part A was rewritten** for the two-file (`main-thread.ts` +
> `background.ts`) architecture this rewrite requires (see the main
> README) — the old single-file main-thread-owned mode it described no
> longer exists. The cold-start numbers in §7 were measured against the
> old architecture and have not been re-measured against this one (an
> extra background thread + patch replay could plausibly change them);
> treat them as methodology, not as current numbers, until re-verified.

This guide documents the complete, real, reproducible procedure this project
uses (verified in `mithril-lynx-ui/demo` + `demo-android`, and in
`indicadores-android` for the font hack) to:

1. Create the JS project that compiles into a Lynx bundle (`mithril-lynx` + `rspeedy`).
2. Create the Android host **from scratch, without Android Studio**, using only the Gradle CLI.
3. Wire the compiled bundle (`.bundle`) into the APK.
4. Build and install the APK from the command line with `adb`.
5. Apply the `.ttf` font-prefetch hack that avoids Lynx's slow `@font-face`
   cold start (a real bug, tracked in
   [lynx-family/lynx#9431](https://github.com/lynx-family/lynx/issues/9431)).

Everything shown here is real code, taken from projects that already work and
have been verified on a physical device (`mithril-lynx-ui/demo-android`,
`indicadores-android`) — it is not an invented, generic tutorial.

---

## Fast path — all of this, automated

Everything this document describes (Parts A, B, C and D) is generated by
`create-mithril-lynx` in a single command. That is the recommended way to
start; the rest of the guide is the reference for *what* each file does and
*why*.

```bash
# JS project + sibling Android host, font hack included:
npm create mithril-lynx@latest my-app --blank --android \
  --android-id com.acme.miapp --app-name "My App" \
  --with-font ~/fonts/ubuntu_mono.ttf

cd my-app
npm install
npm run android       # bundle -> assets -> installDebug -> launch, prints TotalTime
```

Without `--android-id`/`--app-name` it derives them from the project name
(and prompts for them when the CLI runs interactively). Without `--with-font`
none of Part D is generated.

| Flag | What it does |
|---|---|
| `--android` (or `--target android`, or `target=android`) | Generates the sibling Gradle project `<name>-android/` |
| `--android-id <id>` | `applicationId` / `namespace` (default `com.example.<name>`) |
| `--app-name <name>` | Launcher label |
| `--with-font <file.ttf>` | Copies the font into assets, generates `AssetFontFaceLoader.kt`, wires up `prefetchFont()` |
| `--font-family <name>` | Overrides the family name derived from the file name |

What it produces, in terms of this guide's sections:

- **Part A** — the JS project (`package.json`, `lynx.config.ts`, `src/`), with `output.filename = "[name].bundle"` and a `main-thread` entry, i.e. exactly the `dist/main-thread.bundle` the APK expects (section 1).
- **Part B** — a complete `<name>-android/`: `settings.gradle.kts`, `build.gradle.kts`, `gradle.properties`, `local.properties` with `sdk.dir` auto-detected from `ANDROID_HOME`/`ANDROID_SDK_ROOT`, the Gradle wrapper (`gradlew`, `gradlew.bat`, `gradle-wrapper.jar` → Gradle itself does not need to be installed), `app/build.gradle.kts` with the dependencies from 2.7, `AndroidManifest.xml`, the resources from 2.9, and the Kotlin classes from 2.10–2.12.
- **Part C** — a `scripts/android.mjs` in the JS project that chains build → sync into `assets/` → Gradle → `adb am start -W`, exposed as `npm run android` / `android:apk` / `android:release` / `android:sync` / `android:keystore` (sections 3 and 3.1), plus the `keystore.properties`-driven release signing from 3.2.
- **Part D** — only with `--with-font`: the font in `app/src/main/assets/fonts/`, the `@font-face` with `asset:///fonts/...` inserted into the JS project's `src/style.css`, `AssetFontFaceLoader.kt`, its registration before `LynxEnv.inst().init()`, and the `prefetchFont()` before `renderTemplateUrl()` (sections 4.2–4.6).

The files the CLI generates are the ones the following sections document — the
CLI is not a parallel path, it is this document mechanized. If the two ever
diverge, this guide is the source of truth.

Unlike the version of this guide `create-mithril-lynx` used to generate,
there is now only one architecture — every template (including `--blank`)
always has both a `main-thread.ts` and a `background.ts` (section 1.3).
Part B's Android host doesn't need to know or care: `MainActivity` only
calls `renderTemplateUrl("main-thread.bundle", "")`, and that single
`.bundle` already contains both threads' code, packaged together.

---

## 0. Prerequisites

| Tool | Version used in this project | Notes |
|---|---|---|
| Node.js | `^20.19.0` or `>=22.12.0` | required by `@lynx-js/rspeedy` |
| JDK | 17 (Temurin) | `sourceCompatibility`/`targetCompatibility` = 17 |
| Android SDK (cmdline-tools) | platform `android-34`, build-tools `34.0.0` | no Android Studio, just the SDK |
| `adb` | the one shipped in `platform-tools` | to install/launch on a device or emulator |

Installing the Android SDK **from the command line only** (no Android Studio):

```bash
# 1. Download the "command line tools" from
#    https://developer.android.com/studio#command-tools
mkdir -p ~/android-sdk/cmdline-tools
unzip commandlinetools-linux-*.zip -d ~/android-sdk/cmdline-tools
mv ~/android-sdk/cmdline-tools/cmdline-tools ~/android-sdk/cmdline-tools/latest

export ANDROID_HOME=~/android-sdk
export PATH="$PATH:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools"

# 2. Install exactly what is needed to build (accept licenses first)
yes | sdkmanager --licenses
sdkmanager "platform-tools" "platforms;android-34" "build-tools;34.0.0"
```

That gives you `adb`, `platforms/android-34` and `build-tools/34.0.0` —
enough to build and sign a debug APK without ever installing the IDE.

---

## 1. Part A — The JS project (mithril-lynx + rspeedy)

This part produces the artifact the APK actually needs: a `.bundle` file
(main-thread/Lepus patch-replay code plus the real background/JS view code,
packaged together by `mithril-lynx/plugin`). Unlike the old single-file
main-thread-owned mode, mithril-lynx now has exactly one architecture:
`main-thread.ts` only replays patches onto real Element PAPI nodes;
`background.ts` runs the real Mithril render — see the main README's
"Why a rewrite" section for why.

### 1.1 `package.json`

```json
{
  "name": "my-app",
  "version": "0.0.1",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "rspeedy dev",
    "build": "rspeedy build"
  },
  "dependencies": {
    "mithril-runtime": "^1.1.0",
    "mithril-lynx": "latest"
  },
  "devDependencies": {
    "@lynx-js/config-rsbuild-plugin": "^0.2.0",
    "@lynx-js/qrcode-rsbuild-plugin": "^0.7.0",
    "@lynx-js/rspeedy": "^0.17.0",
    "@lynx-js/types": "4.1.0",
    "@rsbuild/plugin-type-check": "^1.6.0",
    "@types/mithril": "^2.2.9",
    "typescript": "~5.9.0"
  },
  "engines": {
    "node": "^20.19.0 || >=22.12.0"
  }
}
```

`mithril-lynx` depends on [`mithril-runtime`](https://github.com/carlos-sweb/mithril-runtime)
(a maintained Mithril 2.3.8 fork, not the official `mithril` package —
`m.route`/`m.trust`/`m.request` are stripped there and reimplemented
Lynx-side, see `mithril-lynx`'s own README). It ships these subpaths today:
`mithril-lynx/background`, `mithril-lynx/main-thread`, `mithril-lynx/plugin`,
`mithril-lynx/route`, `mithril-lynx/request`. Gestures, list virtualization,
imperative refs, and a stack navigator existed in the previous mithril-lynx
but haven't been ported to this architecture yet (see the main README's
"Deliberately not carried over" note) — `mithril-lynx-ui` (ready-made
components) has not been re-verified against this rewrite either.

```bash
npm install
```

### 1.2 `lynx.config.ts` (`rspeedy` configuration)

```ts
import path from "node:path";
import { fileURLToPath } from "node:url";

import { pluginLynxConfig } from "@lynx-js/config-rsbuild-plugin";
import { pluginQRCode } from "@lynx-js/qrcode-rsbuild-plugin";
import { defineConfig } from "@lynx-js/rspeedy";
import { pluginTypeCheck } from "@rsbuild/plugin-type-check";

import { pluginMithrilLynx } from "mithril-lynx/plugin";

const projectRoot = path.dirname(fileURLToPath(import.meta.url));

export default defineConfig({
  source: {
    entry: {
      "main-thread": path.join(projectRoot, "src/main-thread.ts"),
    },
  },
  output: {
    distPath: { root: path.join(projectRoot, "dist") },
    filename: "[name].bundle",
    dataUriLimit: Infinity,
  },
  plugins: [
    pluginMithrilLynx(),
    // enableNewGesture: the native gesture arena — mithril-lynx/gesture
    // doesn't exist yet (see 1.1), but `create-mithril-lynx` turns this on
    // by default so the flag is already there once it does.
    // enableCSSRule: needed for a plain `:root { ... }` rule to apply at
    // all — confirmed, not optional for a typical stylesheet.
    pluginLynxConfig({ enableNewGesture: true, enableCSSRule: true }),
    pluginQRCode({ schema: (url) => `${url}?fullscreen=true` }),
    pluginTypeCheck(),
  ],
});
```

### 1.3 The entry points

`mithril-lynx` always needs BOTH files below — there is no mode where one
is optional (unlike the previous mithril-lynx, which had a main-thread-owned
mode needing only the first).

`src/main-thread.ts` — no app code, ever; only starts the patch-replay
runtime:

```ts
import { setupRenderer } from "mithril-lynx/main-thread";

setupRenderer();
```

`src/background.ts` — where the app actually mounts. This is where
`renderApp()` is called and where all view code lives:

```ts
import m from "mithril-runtime";
import { renderApp } from "mithril-lynx/background";

const Root = {
  view: () =>
    m("view", { class: "Page" }, [
      m("text", { class: "Title" }, "Hello from mithril-lynx"),
    ]),
};

renderApp({ root: () => m(Root) });
```

A tap handler that mutates state repaints the screen with no explicit
`redraw()` call anywhere — mithril-lynx redraws automatically after any
event, same contract real Mithril has always had.

`src/style.css`:

```css
.Page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}
```

`src/rspeedy-env.d.ts` (ambient types, TypeScript only):

```ts
/// <reference types="@lynx-js/rspeedy/client" />
/// <reference types="@lynx-js/types" />
/// <reference types="@lynx-js/type-element-api" />
```

`mithril-runtime` has no published types of its own yet — a project needs a
small ambient module declaration aliasing `@types/mithril`'s shape onto it
(see `create-mithril-lynx`'s `templates/_shared/ts/src/mithril-runtime.d.ts`
for the exact file, including the caveat about which real-Mithril APIs it
over-declares as present).

### 1.4 Building the bundle

```bash
npm run build
```

This produces `dist/main-thread.bundle` — a single binary file containing BOTH
the main-thread (Lepus) code AND the background (JS) code, encoded together.
That is the file the APK needs to package.

---

## 2. Part B — The Android project, from scratch, Gradle CLI only

None of these steps needs Android Studio — it is all text files and
`./gradlew` from the terminal.

### 2.1 Folder structure

```
my-app-android/
├── settings.gradle.kts
├── build.gradle.kts
├── gradle.properties
├── local.properties
├── gradle/wrapper/gradle-wrapper.properties
└── app/
    ├── build.gradle.kts
    └── src/main/
        ├── AndroidManifest.xml
        ├── assets/                      ← the .bundle goes here
        ├── java/com/myapp/
        │   ├── MyApp.kt                 ← Application
        │   ├── MainActivity.kt
        │   └── AssetTemplateProvider.kt
        └── res/
            ├── values/strings.xml
            ├── values/themes.xml
            ├── drawable/ic_launcher_background.xml
            ├── drawable/ic_launcher_foreground.xml
            └── mipmap-anydpi-v26/ic_launcher.xml
```

```bash
mkdir -p my-app-android/app/src/main/{assets,java/com/myapp,res/values,res/drawable,res/mipmap-anydpi-v26}
mkdir -p my-app-android/gradle/wrapper
```

### 2.2 `settings.gradle.kts` (root)

```kotlin
pluginManagement {
    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }
}

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
    }
}

rootProject.name = "my-app-android"
include(":app")
```

### 2.3 `build.gradle.kts` (root)

```kotlin
plugins {
    id("com.android.application") version "8.5.2" apply false
    id("org.jetbrains.kotlin.android") version "1.9.24" apply false
}
```

### 2.4 `gradle.properties`

```properties
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
android.useAndroidX=true
kotlin.code.style=official
```

### 2.5 `local.properties`

```properties
sdk.dir=/path/to/your/android-sdk
```

### 2.6 The Gradle wrapper (without Android Studio)

If you already have Gradle installed somewhere (or `sdkmanager` doesn't ship
it), generate the wrapper directly:

```bash
cd my-app-android
gradle wrapper --gradle-version 8.14.2
```

That creates `gradlew`, `gradlew.bat` and
`gradle/wrapper/gradle-wrapper.properties`. If you don't have Gradle installed
locally, you can write `gradle-wrapper.properties` by hand and Gradle will
download the wrapper `.jar` the first time you run `./gradlew`:

```properties
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.2-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
```

(in that case you also need the `gradlew`/`gradlew.bat` scripts and
`gradle/wrapper/gradle-wrapper.jar`, which you can copy from any existing
Gradle project or generate once with `gradle wrapper` on a machine that does
have Gradle).

### 2.7 `app/build.gradle.kts` — Lynx's real dependencies

```kotlin
plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
}

android {
    namespace = "com.myapp"
    compileSdk = 34

    defaultConfig {
        applicationId = "com.myapp"
        minSdk = 24
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"
    }

    buildTypes {
        debug {
            isMinifyEnabled = false
        }
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }

    kotlinOptions {
        jvmTarget = "17"
    }
}

dependencies {
    // The core artifact — LynxView, LynxViewBuilder, the layout engine, etc.
    implementation("org.lynxsdk.lynx:lynx:4.1.0")

    // OPT-IN, add them only if you use them:

    // <input>/<textarea> — without these those elements take up zero size
    // and never open the keyboard. They are not part of the core artifact.
    implementation("org.lynxsdk.lynx:xelement:4.1.0")
    implementation("org.lynxsdk.lynx:xelement-input:4.1.0")

    // <overlay> — without this the element mounts without error but is never
    // visible (mithril-lynx-ui's Dialog/Sheet/Popover need it).
    implementation("org.lynxsdk.lynx:xelement-overlay:4.1.0")

    // Without a registered ILynxLogService, console.log() and JS errors from
    // the bundle are silently dropped — logcat won't show them either.
    implementation("org.lynxsdk.lynx:lynx-service-log:4.1.0")

    // <refresh> (pull-to-refresh, inside the xelement artifact) internally
    // depends on SmartRefreshLayout, whose touch-dispatch code references
    // ViewPager2 even though you don't use it — without this, every touch on
    // a <refresh> throws NoClassDefFoundError (silently caught by the Lynx
    // engine, but the refresh gesture then simply never works).
    implementation("androidx.viewpager2:viewpager2:1.1.0")

    implementation("androidx.appcompat:appcompat:1.7.0")
    implementation("androidx.core:core-splashscreen:1.0.1")
}
```

### 2.8 `AndroidManifest.xml`

```xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name=".MyApp"
        android:allowBackup="true"
        android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:hardwareAccelerated="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/AppTheme">

        <activity
            android:name=".MainActivity"
            android:theme="@style/Theme.App.Starting"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>
```

### 2.9 Minimum resources needed to compile

`res/values/strings.xml`:

```xml
<resources>
    <string name="app_name">My App</string>
</resources>
```

`res/values/themes.xml`:

```xml
<resources>
    <style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar" />

    <style name="Theme.App.Starting" parent="Theme.SplashScreen">
        <item name="windowSplashScreenBackground">#0F1115</item>
        <item name="postSplashScreenTheme">@style/AppTheme</item>
    </style>
</resources>
```

`res/mipmap-anydpi-v26/ic_launcher.xml` (minimal adaptive icon):

```xml
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
    <background android:drawable="@drawable/ic_launcher_background" />
    <foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
```

`res/drawable/ic_launcher_background.xml` (a flat color will do):

```xml
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="108dp" android:height="108dp"
    android:viewportWidth="108" android:viewportHeight="108">
    <path android:pathData="M0,0h108v108h-108z" android:fillColor="#0F1115" />
</vector>
```

`res/drawable/ic_launcher_foreground.xml` (any simple vector):

```xml
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="108dp" android:height="108dp"
    android:viewportWidth="108" android:viewportHeight="108">
    <path
        android:pathData="M30,54 L50,74 L78,34"
        android:strokeColor="#6EE7B7"
        android:strokeWidth="6"
        android:strokeLineCap="round"
        android:strokeLineJoin="round" />
</vector>
```

(you also need `mipmap-anydpi-v26/ic_launcher_round.xml`, identical to the
`ic_launcher.xml` above).

### 2.10 `MyApp.kt` — the `Application` class

```kotlin
package com.myapp

import android.app.Application
import com.lynx.service.log.LynxLogService
import com.lynx.tasm.LynxEnv
import com.lynx.tasm.service.LynxServiceCenter

class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        // Register the log service BEFORE LynxEnv.inst().init() — without
        // this, console.log() and JS errors from the bundle never show up,
        // not even in logcat. Drop it in a production build if you don't
        // need it.
        LynxServiceCenter.inst().registerService(LynxLogService)
        LynxLogService.switchLogToSystem(true)

        LynxEnv.inst().init(this, null, null, null)
    }
}
```

### 2.11 `AssetTemplateProvider.kt` — reading the bundle WITHOUT blocking the UI thread

```kotlin
package com.myapp

import android.content.Context
import com.lynx.tasm.provider.AbsTemplateProvider
import java.io.IOException

// Reads the bundle on a separate thread. Measured on a real device: reading
// the same asset SYNCHRONOUSLY in MainActivity.onCreate() (blocking Android's
// UI thread — distinct from Lynx's internal main/background thread split, but
// just as harmful to the first frame) cost 2.4-2.8s of cold start; with this
// async provider, ~300ms.
class AssetTemplateProvider(private val context: Context) : AbsTemplateProvider() {
    override fun loadTemplate(url: String, callback: Callback) {
        Thread {
            try {
                val bytes = context.assets.open(url).use { it.readBytes() }
                callback.onSuccess(bytes)
            } catch (e: IOException) {
                callback.onFailed(e.toString())
            }
        }.start()
    }
}
```

### 2.12 `MainActivity.kt` — mounting the `LynxView`

```kotlin
package com.myapp

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import com.lynx.tasm.LynxViewBuilder
import com.lynx.tasm.ThreadStrategyForRendering

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // Must be called BEFORE super.onCreate() — a Splash Screen API
        // requirement.
        installSplashScreen()
        super.onCreate(savedInstanceState)

        val builder = LynxViewBuilder()
        // If you use <input>/<textarea>, also:
        // builder.addBehaviors(com.lynx.xelement.XElementBehaviors().create())
        builder.setThreadStrategyForRendering(ThreadStrategyForRendering.ALL_ON_UI)
        builder.setTemplateProvider(AssetTemplateProvider(this))
        val lynxView = builder.build(this)
        setContentView(lynxView)

        // "main-thread.bundle" must exist in app/src/main/assets/ — see
        // section 3 of this guide.
        lynxView.renderTemplateUrl("main-thread.bundle", "")
    }
}
```

---

## 3. Part C — Wiring the JS bundle into the APK

This is the step that joins the two previous parts: the `.bundle` produced by
`rspeedy` (Part A) has to end up inside `app/src/main/assets/` (Part B) **with
the same name** you pass to `renderTemplateUrl(...)`.

```bash
# 1. Build the JS bundle
npm --prefix my-app-js run build

# 2. Copy it into the Android assets (same name as renderTemplateUrl)
mkdir -p my-app-android/app/src/main/assets
cp my-app-js/dist/main-thread.bundle my-app-android/app/src/main/assets/main-thread.bundle

# 3. Build and install the debug APK on the connected device/emulator
cd my-app-android
./gradlew installDebug

# 4. Launch it
adb shell am force-stop com.myapp
adb shell am start -W -n com.myapp/.MainActivity
```

`./gradlew installDebug` builds `app-debug.apk` (with the `debug.keystore`
AGP generates for you, signed automatically) and installs it straight onto the
connected device — no need to go through `adb install` by hand, though that
works too:

```bash
./gradlew assembleDebug   # build only, don't install
adb install -r app/build/outputs/apk/debug/app-debug.apk
```

### 3.1 All-in-one script

This is how this very project chains the 4 steps into a single command
(`mithril-lynx-ui/demo.sh`):

```bash
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"

npm --prefix my-app-js run build
mkdir -p my-app-android/app/src/main/assets
cp my-app-js/dist/main-thread.bundle my-app-android/app/src/main/assets/main-thread.bundle

(cd my-app-android && ./gradlew --quiet installDebug)

adb shell am force-stop com.myapp
adb shell am start -W -n com.myapp/.MainActivity | grep -E "TotalTime|LaunchState"
```

`am start -W` blocks until the Activity finishes drawing its first frame and
prints `TotalTime`/`WaitTime` — the real way to measure cold start from the
command line, with no extra instrumentation.

### 3.2 Release APK (signed)

```bash
# Generate a keystore (once)
keytool -genkey -v -keystore release.keystore -alias my-app \
  -keyalg RSA -keysize 2048 -validity 10000

# In app/build.gradle.kts, inside android { }:
#   signingConfigs {
#       create("release") {
#           storeFile = file("../release.keystore")
#           storePassword = System.getenv("KEYSTORE_PASSWORD")
#           keyAlias = "my-app"
#           keyPassword = System.getenv("KEY_PASSWORD")
#       }
#   }
#   buildTypes {
#       release {
#           signingConfig = signingConfigs.getByName("release")
#           isMinifyEnabled = true
#       }
#   }

KEYSTORE_PASSWORD=... KEY_PASSWORD=... ./gradlew assembleRelease
# Final APK: app/build/outputs/apk/release/app-release.apk
```

#### 3.2.1 `isMinifyEnabled = true` breaks both the build and the runtime (verified)

This part of the guide used to be incomplete, and it cost two real bugs. Both
were found by building and installing a **minified** release on a Galaxy A07
(`assembleRelease` + R8, `lynx:4.1.0` + AGP 8.5.2). If you turn on
`isMinifyEnabled = true` without the fixes below, you do not end up with a
working APK.

**Bug 1 — R8 aborts the build.** The `xelement` artifact references
**optional** dependencies that are not on the classpath (Fresco, Gson, the
Markdown module), and in full mode R8 fails with `Missing classes detected
while running R8`. AGP writes the exact names to
`app/build/outputs/mapping/release/missing_rules.txt`, but it is better to
ignore whole packages so it does not break again with the next SDK release:

```proguard
-dontwarn com.facebook.**
-dontwarn com.google.gson.**
-dontwarn com.lynx.markdown.**
```

**Bug 2 — the APK builds but crashes on startup.** The `lynx-base` AAR calls
`com.lynx.base.log.LynxLog.log(int, String, String, int, long, int, int)` from
C++ via JNI `GetStaticMethodID`. That class is not annotated with
`@CalledByNative` (unlike almost the whole bridge), so the *consumer* rules
the `lynx` AAR does ship — `lynx-base` contributes none for this — do not
cover it, R8 renames it, and the process dies **before drawing anything**:

```
java.lang.NoSuchMethodError: no static method
  "Lcom/lynx/base/log/LynxLog;.log(ILjava/lang/String;Ljava/lang/String;IJII)V"
FATAL: JNI DETECTED ERROR IN APPLICATION: mid == null
Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid (LynxTraceInit)
```

The rule that fixes it:

```proguard
-keep class com.lynx.base.log.LynxLog { *; }
```

Upstream this is still **open** with no official answer
([lynx-family/lynx#695](https://github.com/lynx-family/lynx/issues/695), open
since 2025-04, with the team pointing people at "use the demo", which
curiously ships no ProGuard rules either). The `proguard-rules.pro` that
`create-mithril-lynx` generates has both fixes in place and commented.

Verifying the fix, on a real device, with the **minified release** APK:

```bash
./gradlew assembleRelease
adb install -r app/build/outputs/apk/release/app-release.apk
adb shell am start -W -n com.myapp/.MainActivity
```

Zero `FATAL`/`SIGABRT`/`NoSuchMethodError`, and
`FontFaceManager: prefetchFont success: asset:///fonts/ubuntu_mono.ttf` in
logcat — i.e. Part D survives minification.

If your app registers its own native modules
(`builder.registerModule("X", X::class.java)`) or behaviors reached by
reflection, add `-keep` rules for those too: the AAR cannot know they exist.

#### 3.2.2 Minification is worth it for cold start, not just APK size

Same device, same app, `am start -W`, `LaunchState: COLD`, after a
`force-stop`:

| Build | Cold start (steady state) |
|---|---|
| `debug` (no minification) | 746–829 ms |
| `release` (R8, minified) | 246–272 ms |

Roughly a 3x difference on a budget device. Measuring cold start against a
debug build is measuring the wrong build — the numbers you'd be optimizing
have little to do with what users get. Section 7 has the full table.

### 3.3 Installing the APK: two things that bite on real devices

Neither of these is a bug in your app, but both cost time if you don't expect
them.

**`./gradlew installDebug` can fail with `InstallException: EOF`.** The
debug APK is fat (all ABIs, see below), and `ddmlib`'s streamed install over
USB occasionally drops it. The failure looks alarming and is not:

```
Execution failed for task ':app:installDebug'.
> com.android.ddmlib.InstallException: EOF
```

Retrying the same command usually works, and going around Gradle works
immediately:

```bash
adb install -r app/build/outputs/apk/debug/app-debug.apk
```

**APKs are large — 71 MB debug / 65 MB release for a "Hello World".** That is
Lynx shipping its native libraries (`.so`) for every ABI plus the QuickJS/V8
bridges; it is not your bundle. Measured on the generated Blank project: **72
shared libraries** inside a single APK. Check yours with:

```bash
unzip -l app/build/outputs/apk/debug/app-debug.apk | grep '\.so$' | wc -l
# 72
```

To ship a reasonable APK, use an App Bundle (`./gradlew bundleRelease`, which
lets Play split by ABI and density) or `splits { abi { ... } }` in
`app/build.gradle.kts`. The difference is not marginal — same project, same
code:

| Artifact | Size |
|---|---|
| `app-debug.apk` | 71.3 MB |
| `app-release.apk` (R8 minified, all ABIs) | 65.5 MB |
| `app-release.aab` (`./gradlew bundleRelease`) | 29.5 MB |

...and the 29.5 MB is what you upload; what a given device downloads is smaller
still, because Play delivers only the ABI and density that device needs. Just
don't be surprised by the APK size when testing locally.

**Android 15+/One UI shows a "16 KB page size" compatibility dialog.** On
recent Samsung firmware (and any Android 15+ device with 16 KB pages), the
first launch after installing pops a full-screen system warning:

> This app is not compatible with 16 KB. ELF alignment could not be verified.
> The following libraries are not aligned to 16 KB: `libanimax.so`,
> `libharfbuzz.so`, `libnapi_v8.so`, …

It lists Lynx's prebuilt `.so` files. It is a system dialog, not your app's
Activity, it appears in front of your UI (making a naive screenshot look
wrong), and it can be dismissed with "OK". Nothing in the Android host can fix
it — the alignment lives inside the native libraries the Lynx SDK ships. When
scripting device tests, either tap it away or assert on logcat instead of on a
screenshot.

---

## 4. Part D — The `.ttf` font hack (`@font-face` prefetch)

### 4.1 The problem

A custom `@font-face` in Lynx (confirmed on `org.lynxsdk.lynx:lynx:4.1.0`, and
also reproduced in ReactLynx — it is not a mithril-lynx bug) is resolved
**synchronously inside the first native call to `__FlushElementTree()`**, and
that cost scales with how many text nodes end up resolving that font family —
up to +2s of cold start measured on a mid/low-end device (Samsung Galaxy A07)
with the font applied through a plain `text { font-family: ...; }` selector.

Reported upstream:
[lynx-family/lynx#9431](https://github.com/lynx-family/lynx/issues/9431).

**The fix**: instead of letting `@font-face` resolve the first time layout
needs it, *prefetch* the `Typeface` from Kotlin **before**
`renderTemplateUrl()` even starts the bundle — so when the real CSS asks for
that font during the first layout, it is already cached and resolution is
instant.

Measured on the same device, with the font applied to the broadest possible
selector (`text { font-family: ...; }`, every text node): from ~1.4-2.9s down
to **~750-800ms — indistinguishable from the baseline with no custom font.**

### 4.2 Step 1 — the `.ttf` goes in `assets/fonts/`

```bash
mkdir -p app/src/main/assets/fonts
cp ubuntu_mono.ttf app/src/main/assets/fonts/ubuntu_mono.ttf
```

### 4.3 Step 2 — declare `@font-face` with `asset:///` in your CSS

In the **JS** project's `style.css` (the one `@import`ed by `lynx.config.ts`),
not in Android:

```css
@font-face {
  font-family: "Ubuntu Mono";
  src: url("asset:///fonts/ubuntu_mono.ttf");
}

text {
  font-family: "Ubuntu Mono", sans-serif;
}
```

The string `asset:///fonts/ubuntu_mono.ttf` must be **byte-for-byte identical**
to the one you use in `prefetchFont()` (step 4.5) — Lynx caches the
prefetched `Typeface` using that exact string as the key.

### 4.4 Step 3 — register a `LynxFontFaceLoader.Loader` that can resolve `asset:///`

Lynx's default loader (decompiled from `lynx-4.1.0.aar`) **does not resolve
`asset:///` in any way** — neither for the prefetch nor for the real
resolution — unless you register your own:

```kotlin
package com.myapp

import android.graphics.Typeface
import com.lynx.tasm.behavior.LynxContext
import com.lynx.tasm.fontface.FontFace
import com.lynx.tasm.loader.LynxFontFaceLoader

object AssetFontFaceLoader : LynxFontFaceLoader.Loader() {
    private const val ASSET_PREFIX = "asset:///"

    override fun onLoadFontFace(
        context: LynxContext,
        type: FontFace.TYPE,
        src: String,
    ): Typeface? {
        if (!src.startsWith(ASSET_PREFIX)) return null
        return try {
            Typeface.createFromAsset(context.context.assets, src.removePrefix(ASSET_PREFIX))
        } catch (e: Exception) {
            null
        }
    }
}
```

### 4.5 Step 4 — register the loader BEFORE `LynxEnv.inst().init()`

In your `Application.onCreate()` (`MyApp.kt` from section 2.10):

```kotlin
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()

        LynxServiceCenter.inst().registerService(LynxLogService)
        LynxLogService.switchLogToSystem(true)

        // MUST come before LynxEnv.inst().init() — this is what makes
        // "asset:///" resolvable, both by the prefetch and by the real
        // @font-face resolution.
        LynxFontFaceLoader.setLoader(AssetFontFaceLoader)

        LynxEnv.inst().init(this, null, null, null)
    }
}
```

### 4.6 Step 5 — `prefetchFont()` BEFORE `renderTemplateUrl()`

In `MainActivity.kt`, right after `builder.build(this)` and BEFORE
`lynxView.renderTemplateUrl(...)`:

```kotlin
import com.lynx.tasm.fontface.FontFaceManager

// ...
val lynxView = builder.build(this)
setContentView(lynxView)

FontFaceManager.getInstance().prefetchFont(
    lynxView.lynxContext,
    "asset:///fonts/ubuntu_mono.ttf",   // identical to the CSS src: url(...)
    null,
    object : FontFaceManager.FontFacePrefetchListener {
        override fun onComplete(code: Int, msg: String) {}
    },
)

lynxView.renderTemplateUrl("main-thread.bundle", "")
```

`prefetchFont()` runs on Lynx's own IO thread pool — it blocks nothing. If the
race against the first layout is won (the normal case, since the bundle's JS
hasn't even started executing yet) there is no visible fallback-font flash; if
it is somehow lost, it simply degrades to the normal behavior (the font
resolves where it always did, nothing breaks).

**How to confirm it actually ran.** Lynx logs one line per prefetch on
success, and it is the cheapest end-to-end check for the whole Part D:

```bash
adb logcat | grep FontFaceManager
# I FontFaceManager: prefetchFont success: asset:///fonts/ubuntu_mono.ttf
```

If you don't see that line, the loader is not registered, the URI doesn't
match the CSS byte-for-byte, or the `.ttf` isn't in the APK's assets.

### 4.7 Why this path and not the documented JS APIs

Lynx documents `lynx.addFont()` and
`lynx.requestResourcePrefetch({type:"font"})`, both callable from JS. **They
do not solve this problem**: they are invoked from a post-mount hook, meaning
the engine already has to be up and running for either of them to fire — they
cannot win the *first* frame race. On top of that, every official example
points at a font served over HTTPS, never at a packaged local asset.

The native (Kotlin) path runs **before the JS engine even starts**, so there
is no window in which the fallback is visible.

**Trade-off to keep in mind**: `FontFaceManager`/`LynxFontFaceLoader` are
public classes (not `@RestrictTo`) but are not documented for this specific
use — they could change without notice in a future major version of the Lynx
SDK, unlike the official JS API surface.

---

## 5. Cheatsheet — quick reference commands

```bash
# Build the JS bundle
npm --prefix my-app-js run build

# Copy it into Android
cp my-app-js/dist/main-thread.bundle my-app-android/app/src/main/assets/main-thread.bundle

# Build + install on the connected device
(cd my-app-android && ./gradlew installDebug)

# Restart and measure cold start
adb shell am force-stop com.myapp
adb shell am start -W -n com.myapp/.MainActivity

# Watch logs live (requires LynxLogService registered, see 2.10)
adb logcat | grep -i lynx

# Confirm the font prefetch ran (Part D)
adb logcat | grep FontFaceManager

# Confirm the bundle actually executed
adb logcat | grep __RenderPage

# Build the APK without installing
(cd my-app-android && ./gradlew assembleDebug)
# → my-app-android/app/build/outputs/apk/debug/app-debug.apk

# If installDebug dies with "InstallException: EOF" (see 3.3)
adb install -r my-app-android/app/build/outputs/apk/debug/app-debug.apk

# Clean the build (if something got into a weird state)
(cd my-app-android && ./gradlew clean)

# See which devices/emulators are connected
adb devices -l
```

### 5.1 All of the above, via the CLI

If the project came out of `create-mithril-lynx --android`, the steps above are
npm scripts in the JS project:

```bash
npm run android:sync     # = build + cp into assets (sections 1.4 and 3)
npm run android          # = sync + installDebug + am start -W (section 3.1)
npm run android:apk      # = sync + assembleDebug
npm run android:release  # = sync + assembleRelease (sections 3.2 and 3.2.1)
npm run android:keystore # = keytool + keystore.properties (section 3.2)
```

`npm run android` prints `TotalTime` directly, already grepped, and tells you
the APK path for `android:apk`/`android:release`.

---

## 6. Troubleshooting

| Symptom | Cause | Fix |
|---|---|---|
| `<input>`/`<textarea>` take up zero size, never open the keyboard | Missing `xelement`/`xelement-input`, or missing `builder.addBehaviors(XElementBehaviors().create())` | Sections 2.7 and 2.12 |
| `<overlay>` mounts but nothing is ever visible | Missing `xelement-overlay` | Section 2.7 |
| A raw native gesture (`__SetGestureDetector`) never fires, with no error | Missing `pluginLynxConfig({ enableNewGesture: true })` in `lynx.config.ts` (`mithril-lynx/gesture` itself doesn't exist yet, see 1.1) | Section 1.2 |
| `console.log()` / JS errors appear nowhere | Missing `lynx-service-log` + `LynxServiceCenter.inst().registerService(LynxLogService)` | Sections 2.7 and 2.10 |
| Touching a `<refresh>` throws `NoClassDefFoundError` (caught, the gesture just never works) | Missing `androidx.viewpager2:viewpager2` | Section 2.7 |
| Cold start of 2+ seconds | Bundle read synchronously on the UI thread | Use the async `AssetTemplateProvider` (2.11), never a direct `context.assets.open(...)` in `onCreate()` |
| Custom `@font-face` adds +1-2s of cold start | Synchronous resolution inside `__FlushElementTree()` — known bug | All of Part D |
| `asset:///...` resolves neither in `prefetchFont()` nor in the real CSS | Missing `LynxFontFaceLoader.setLoader(...)`, or it was registered after `LynxEnv.inst().init()` | Section 4.5 |
| No `FontFaceManager: prefetchFont success:` line in logcat | Loader not registered, URI not byte-identical to the CSS `src: url(...)`, or the `.ttf` isn't in the APK's assets | Sections 4.3–4.6 |
| `./gradlew` fails with "SDK location not found" | Missing `local.properties` with `sdk.dir=...` | Section 2.5 |
| `./gradlew installDebug` fails with `com.android.ddmlib.InstallException: EOF` | `ddmlib`'s streamed install over USB dropped the fat debug APK. Transient | Retry, or `adb install -r app/build/outputs/apk/debug/app-debug.apk` (section 3.3) |
| `assembleRelease` fails with `Missing classes detected while running R8` | `xelement` references Fresco/Gson/Markdown, optional dependencies outside the classpath | Section 3.2.1 — the `-dontwarn` rules |
| The release APK builds but crashes on startup with `NoSuchMethodError: ...LynxLog;.log(...)` / `JNI DETECTED ERROR: mid == null` / `SIGABRT` in the `LynxTraceInit` thread | R8 renames `com.lynx.base.log.LynxLog`, which native code calls by exact name via JNI; the AAR does not annotate it `@CalledByNative` | Section 3.2.1 — `-keep class com.lynx.base.log.LynxLog { *; }` |
| A full-screen "not compatible with 16 KB" dialog covers the app on Android 15+/One UI | System warning about Lynx's prebuilt, non-16K-aligned `.so` files. Not your app | Dismiss it; see section 3.3. Assert on logcat, not screenshots, in device tests |
| SDK license errors while building | Licenses not accepted | `yes \| sdkmanager --licenses` |

---

## 7. What was verified on device

All of the following was measured on a Samsung Galaxy A07 (SM-A075M, Android
15/One UI), with a project generated by
`npm create mithril-lynx@latest --ts --blank --android --with-font`, installed
over USB with `adb`.

Cold start via `adb shell am start -W`, after `am force-stop` and a settle
delay, `LaunchState: COLD`:

| Build | First launch after install | Steady state |
|---|---|---|
| `debug` (`assembleDebug` / `installDebug`) | 2610 ms | 746, 750, 764, 829 ms |
| `release` (R8 minified, signed) | 576 ms | 246, 260, 263, 272 ms |

The first launch after a fresh install is always the slowest one (dexopt/AOT
warm-up) — that number is real but not representative, which is why it is
listed separately.

Other things confirmed on the same device:

- `FontFaceManager: prefetchFont success: asset:///fonts/ubuntu_mono.ttf` in
  logcat, in both debug and minified release (Part D survives R8).
- `LepusClosureEventListener::Invoke name: __RenderPage` in logcat — the
  bundle's main-thread entry actually ran.
- Zero `FATAL` / `SIGABRT` / `NoSuchMethodError` in logcat across debug,
  minified release, and every relaunch.
- The Hello World template renders (`Mithril` / `on Lynx` / "Tap the logo and
  have fun!") and so does the Blank template.
- `aapt2 dump badging` on the built APK shows the expected
  `package`, `application-label`, `sdkVersion:'24'`, `targetSdkVersion:'34'`.
- The `.bundle` copied by the CLI is byte-identical to `dist/main-thread.bundle`
  (47806 bytes in the Blank case), and the `.ttf` is packaged at
  `assets/fonts/` inside the APK.
- `apksigner verify` confirms the release APK is signed with the generated
  keystore.
