⫶ On this page

Native Android Apps in Rust with egui

This tutorial walks through building a native Android app in Rust using egui for the UI, cargo-apk for packaging, and the Android NDK for compilation. It covers both a manual setup and a Nix flake approach, then shows how to call into Android APIs via JNI and bundle an AAR library.

What you need

  • Rust and rustup
  • Android SDK and NDK (command-line tools only, no Android Studio required)
  • Java (for sdkmanager and signing)
  • A connected Android device or emulator with USB debugging enabled

Android SDK setup

Manual

Download the command-line tools for your platform from developer.android.com/studio:

Download the Linux command-line tools from developer.android.com/studio:

https://dl.google.com/android/repository/commandlinetools-linux-14742923_latest.zip

Extract and install the SDK components:

export ANDROID_HOME="$HOME/android-sdk"
mkdir -p "$ANDROID_HOME/cmdline-tools"
curl -sLo /tmp/clt.zip https://dl.google.com/android/repository/commandlinetools-linux-14742923_latest.zip
unzip /tmp/clt.zip -d "$ANDROID_HOME/cmdline-tools"
mv "$ANDROID_HOME/cmdline-tools/cmdline-tools" "$ANDROID_HOME/cmdline-tools/latest"
export PATH="$PATH:$ANDROID_HOME/cmdline-tools/latest/bin"

sdkmanager --sdk_root="$ANDROID_HOME" --install \
  "build-tools;36.0.0" \
  "ndk;29.0.14206865" \
  "platforms;android-35"

export ANDROID_NDK_ROOT="$ANDROID_HOME/ndk/29.0.14206865"
export JAVA_HOME="/path/to/jdk"

JAVA_HOME is required by apksigner when signing the APK. On a system with Android Studio installed it is at ~/android-studio/jbr. Add all the exports to your shell profile so they persist across sessions.

Nix flake

If you use Nix, the following flake.nix sets up a reproducible shell with the SDK, NDK, and Rust targets:

{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    flake-utils.url = "github:numtide/flake-utils";
    android-nixpkgs = {
      url = "github:tadfisher/android-nixpkgs";
      inputs.nixpkgs.follows = "nixpkgs";
    };
  };

  outputs = { self, nixpkgs, flake-utils, android-nixpkgs }:
    flake-utils.lib.eachDefaultSystem (system:
      let
        pkgs = nixpkgs.legacyPackages.${system};
        androidSdk = android-nixpkgs.sdk.${system} (sdkPkgs: with sdkPkgs; [
          build-tools-36-0-0
          ndk-29-0-14206865
          platforms-android-35
          cmdline-tools-latest
        ]);
      in {
        devShells.default = pkgs.mkShell {
          buildInputs = with pkgs; [
            rustup
            jdk17
            androidSdk
          ];
          shellHook = ''
            export ANDROID_HOME="${androidSdk}/share/android-sdk"
            export ANDROID_NDK_ROOT="$ANDROID_HOME/ndk/29.0.14206865"
            export PATH="$PATH:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/build-tools/36.0.0"
          '';
        };
      });
}

Enter the shell with nix develop.

Rust setup

Add the Android targets via rustup:

rustup target add \
  aarch64-linux-android \
  armv7-linux-androideabi \
  x86_64-linux-android \
  i686-linux-android

aarch64-linux-android covers most modern devices. The armv7 target is for older 32-bit devices.

Install cargo-apk from rust-mobile/cargo-apk:

cargo install cargo-apk

Hello world with egui

Project structure

cargo new --lib hello-android
cd hello-android

The app is a Rust cdylib that Android loads as a native library. Add the dependencies:

cargo add egui
cargo add eframe --no-default-features --features android-native-activity,glow
cargo add winit

Cargo.toml

[package]
name = "hello-android"
version = "0.1.0"
edition = "2024"

[lib]
crate-type = ["cdylib"]

[dependencies]
egui = "0.33"
eframe = { version = "0.33", default-features = false, features = [
  "android-native-activity",
  "glow",
] }
winit = "0.30"

[package.metadata.android]
package = "nl.example.helloandroid"
label = "Hello Android"
build_targets = ["aarch64-linux-android"]

[package.metadata.android.sdk]
min_sdk_version = 26
target_sdk_version = 35

src/lib.rs

#![cfg(target_os = "android")]

use winit::platform::android::activity::AndroidApp;

#[no_mangle]
fn android_main(app: AndroidApp) {
    let options = eframe::NativeOptions {
        android_app: Some(app),
        ..Default::default()
    };

    eframe::run_native(
        "Hello Android",
        options,
        Box::new(|_cc| Ok(Box::new(HelloApp::default()))),
    )
    .unwrap();
}

#[derive(Default)]
struct HelloApp;

impl eframe::App for HelloApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.heading("Hello from Rust");
            ui.label("Running on Android via egui.");
        });
    }
}

Build and run

cargo apk run --lib

This builds the APK, installs it on the connected device, and launches it. For a release build:

cargo apk build --lib --release

The APK is written to target/release/apk/.

Calling Android APIs via JNI

Rust code running in a cdylib can call Java APIs through JNI. The jni crate provides safe bindings.

cargo add jni

The Android runtime passes a JavaVM pointer at startup. Store it and use it to call Java methods:

use jni::{JNIEnv, JavaVM};
use jni::objects::{JClass, JString};
use jni::sys::jstring;

#[no_mangle]
pub extern "C" fn Java_nl_example_helloandroid_MainActivity_getDeviceModel(
    mut env: JNIEnv,
    _class: JClass,
) -> jstring {
    let model = env
        .find_class("android/os/Build")
        .and_then(|cls| env.get_static_field(cls, "MODEL", "Ljava/lang/String;"))
        .and_then(|v| v.l())
        .and_then(|obj| env.get_string(&JString::from(obj)))
        .map(|s| s.into())
        .unwrap_or_else(|_| String::from("unknown"));

    env.new_string(model).unwrap().into_raw()
}

The function name follows the JNI naming convention: Java_<package>_<class>_<method>, with dots replaced by underscores.

Using an AAR library

AAR files are Android library bundles that contain compiled Java/Kotlin code, resources, and native libraries. To use one from Rust you need to extract its JAR and add it to the Java classpath so JNI can find the classes.

Extract the JAR

unzip mylibrary.aar classes.jar -d mylibrary

Reference it in Cargo.toml

[package.metadata.android]
package = "nl.example.helloandroid"
label = "Hello Android"
build_targets = ["aarch64-linux-android"]

[[package.metadata.android.uses_library]]
name = "classes.jar"

Place classes.jar in a libs/ directory at the project root. cargo-apk will bundle it into the APK.

Call the AAR class from Rust via JNI

fn call_aar_method(env: &mut JNIEnv) -> jni::errors::Result<String> {
    let cls = env.find_class("com/example/mylibrary/MyHelper")?;
    let result = env.call_static_method(
        cls,
        "getMessage",
        "()Ljava/lang/String;",
        &[],
    )?;
    let obj = result.l()?;
    let s = env.get_string(&JString::from(obj))?;
    Ok(s.into())
}

The method signature ()Ljava/lang/String; is standard JVM descriptor notation: () means no arguments, Ljava/lang/String; is the return type. You can inspect method signatures with javap -s -p classes.jar.

Including native .so libraries

Sometimes you have a prebuilt C or C++ library (from an SDK, a vendor, or built separately with the NDK) that you want to ship inside the APK and link against from Rust.

There are two separate concerns: bundling the .so into the APK so Android can find it at runtime, and linking against it at build time so the Rust compiler can resolve the symbols.

Folder structure

cargo-apk looks for extra shared libraries under a folder you name, organised by Android ABI:

libs/
  arm64-v8a/
    libmything.so
  armeabi-v7a/
    libmything.so
  x86_64/
    libmything.so

The ABI folder names match the Android ABI strings, not the Rust target triples:

Rust targetAndroid ABI folder
aarch64-linux-androidarm64-v8a
armv7-linux-androideabiarmeabi-v7a
x86_64-linux-androidx86_64
i686-linux-androidx86

Bundling with cargo-apk

Point runtime_libs at the folder in Cargo.toml:

[package.metadata.android]
package = "nl.example.helloandroid"
label = "Hello Android"
resources = "res"
runtime_libs = "libs"
build_targets = ["aarch64-linux-android"]

[package.metadata.android.application]
icon = "@mipmap/ic_launcher"
extract_native_libs = true

extract_native_libs = true is required when loading a .so with System.loadLibrary or Rust's libloading. Without it, Android may keep the library compressed inside the APK and the dynamic linker will not find it.

cargo-apk picks up files matching libs/${android_abi}/*.so for each target in build_targets and adds them to lib/${android_abi}/ inside the APK.

Linking at build time

To link against the library when compiling Rust, add a build script that tells cargo where to find it:

// build.rs
fn main() {
    let target = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
    if target == "android" {
        let abi = match std::env::var("CARGO_CFG_TARGET_ARCH").unwrap().as_str() {
            "aarch64" => "arm64-v8a",
            "arm"     => "armeabi-v7a",
            "x86_64"  => "x86_64",
            "x86"     => "x86",
            other     => panic!("unsupported android arch: {other}"),
        };
        println!("cargo:rustc-link-search=native=libs/{abi}");
        println!("cargo:rustc-link-lib=dylib=mything");
    }
}

Then call into it from Rust via FFI as usual:

unsafe extern "C" {
    fn mything_init() -> i32;
    fn mything_process(data: *const u8, len: usize) -> i32;
}

fn init() {
    let rc = unsafe { mything_init() };
    assert_eq!(rc, 0, "mything_init failed");
}

Loading at runtime with libloading

If you prefer to load the library dynamically at runtime rather than link at build time, use the libloading crate:

cargo add libloading
unsafe {
    let lib = libloading::Library::new("libmything.so").expect("failed to load libmything");
    let init: libloading::Symbol<unsafe extern "C" fn() -> i32> =
        lib.get(b"mything_init").expect("symbol not found");
    init();
}

Android resolves the library name against the directories in LD_LIBRARY_PATH, which includes the APK's lib/${abi}/ directory at runtime.

Higher-level bindings with UniFFI

Writing JNI by hand is tedious and error-prone. Mozilla's UniFFI generates Kotlin and Java bindings from a Rust library automatically, based on a UDL interface definition or proc-macro annotations. It is used in production by Firefox for Android. See the UniFFI user guide for a full walkthrough.

Logging and logcat

Android has its own logging system. The log crate provides the standard Rust logging facade, and android_logger hooks it into Android's logcat output.

cargo add log
cargo add android_logger

Initialise the logger at the start of android_main, before anything else runs:

#![cfg(target_os = "android")]

use log::LevelFilter;
use winit::platform::android::activity::AndroidApp;

#[no_mangle]
fn android_main(app: AndroidApp) {
    android_logger::init_once(
        android_logger::Config::default()
            .with_max_level(LevelFilter::Debug)
            .with_tag("hello-android"),
    );

    log::info!("app starting");

    let options = eframe::NativeOptions {
        android_app: Some(app),
        ..Default::default()
    };

    eframe::run_native(
        "Hello Android",
        options,
        Box::new(|_cc| Ok(Box::new(HelloApp::default()))),
    )
    .unwrap();
}

Then use the standard log macros anywhere in the app:

impl eframe::App for HelloApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {
            ui.heading("Hello from Rust");
            if ui.button("Click me").clicked() {
                log::debug!("button clicked");
            }
        });
    }
}

Reading logs with adb logcat

With a device or emulator connected, stream all output from the app:

adb logcat --pid=$(adb shell pidof nl.example.helloandroid) -v brief

Or filter by the tag set in with_tag:

adb logcat -s hello-android

To see only your app's output from the moment it starts, clear the buffer first:

adb logcat -c && adb logcat -s hello-android

Log levels map to Android priorities as follows:

Rust log levelAndroid priority
error!E
warn!W
info!I
debug!D
trace!V (verbose)

Add a just logs recipe to the justfile to make this easy to invoke:

logs:
    adb logcat -s hello-android

App icon

Android uses PNG icons in a set of density buckets called mipmaps. The standard sizes for ic_launcher.png are:

FolderSize
res/mipmap-mdpi48x48
res/mipmap-hdpi72x72
res/mipmap-xhdpi96x96
res/mipmap-xxhdpi144x144
res/mipmap-xxxhdpi192x192

Start with an SVG and rasterise it to each size using rsvg-convert (from librsvg):

mkdir -p res/mipmap-mdpi res/mipmap-hdpi res/mipmap-xhdpi res/mipmap-xxhdpi res/mipmap-xxxhdpi

rsvg-convert -w 48  -h 48  icon.svg -o res/mipmap-mdpi/ic_launcher.png
rsvg-convert -w 72  -h 72  icon.svg -o res/mipmap-hdpi/ic_launcher.png
rsvg-convert -w 96  -h 96  icon.svg -o res/mipmap-xhdpi/ic_launcher.png
rsvg-convert -w 144 -h 144 icon.svg -o res/mipmap-xxhdpi/ic_launcher.png
rsvg-convert -w 192 -h 192 icon.svg -o res/mipmap-xxxhdpi/ic_launcher.png

If you do not have rsvg-convert, inkscape works too:

inkscape icon.svg -w 192 -h 192 -o res/mipmap-xxxhdpi/ic_launcher.png

Tell cargo-apk where the resources live and which icon to use in Cargo.toml:

[package.metadata.android]
package = "nl.example.helloandroid"
label = "Hello Android"
resources = "res"
build_targets = ["aarch64-linux-android"]

[package.metadata.android.application]
icon = "@mipmap/ic_launcher"

The resources path points to the folder containing the mipmap-* directories. cargo-apk bundles its contents into the APK under res/.

Justfile

A justfile collects the common commands so you do not have to remember the full invocations.

android_home := env("ANDROID_HOME", env("HOME") + "/android-sdk")
avd_name := "pixel_35"
apk := "target/release/apk/hello-android.apk"

android-build:
  cargo apk build --lib --release

android-install: android-build
  adb install -r {{apk}}

android-run:
  cargo apk run --lib

emulator-setup:
  {{android_home}}/cmdline-tools/latest/bin/sdkmanager "system-images;android-35;google_apis;x86_64"
  {{android_home}}/cmdline-tools/latest/bin/avdmanager create avd \
    --name {{avd_name}} \
    --package "system-images;android-35;google_apis;x86_64" \
    --device "pixel_6" \
    --force

emulator-start:
  {{android_home}}/emulator/emulator -avd {{avd_name}} -netdelay none -netspeed full &

emulator-run: emulator-start
  adb wait-for-device
  cargo apk run --lib
  • just android-build - builds a release APK
  • just android-install - builds and installs to a connected device via adb
  • just android-run - builds and runs directly (debug, faster iteration)
  • just emulator-setup - downloads the system image and creates the AVD (run once)
  • just emulator-start - launches the emulator in the background
  • just emulator-run - starts the emulator, waits for it to boot, then installs and runs

Override the AVD name or SDK path without editing the file:

just avd_name=my_avd emulator-run
just android_home=/opt/android-sdk android-build

Running on the emulator

If you do not have a physical device, create an AVD with the Android CLI:

sdkmanager "system-images;android-35;google_apis;x86_64"
avdmanager create avd \
  --name "pixel_35" \
  --package "system-images;android-35;google_apis;x86_64" \
  --device "pixel_6"
emulator -avd pixel_35 -netdelay none -netspeed full &

Wait for the emulator to boot, then run cargo apk run --lib as normal. Add x86_64-linux-android to your rustup targets for emulator builds.

References