ajni

    Android JNI runtime primitives and MoonBit lifecycle bridge.

    moonbit
    android
    jni
    ndk
    Download zip
    Version
    0.2.0
    License
    Apache-2.0
    Last updated
    4 months ago
    Downloads
    871

    No dependencies

    #ajni

    ajni provides MoonBit-facing Android JNI runtime primitives. It supplies a stable Kotlin host, lifecycle and UI-thread callbacks, safe Java UTF-16/MoonBit UTF-8 conversion, and an optional Android WebView feature.

    The core package and WebView feature are separate. Applications that only need lifecycle or UI callbacks import Nanaloveyuki/ajni; applications that embed a browser additionally import Nanaloveyuki/ajni/webview and link its native stub.

    #Install

    moon add Nanaloveyuki/ajni

    For the optional WebView feature, import its package from a MoonBit package:

    import {
    "Nanaloveyuki/ajni/webview",
    }

    #Core Runtime

    Install an event handler before the Kotlin host forwards Activity or Surface events. The handler returns a token that can be removed during shutdown.

    import {
    "Nanaloveyuki/ajni",
    }

    let subscription = @ajni.install_event_handler(event => match event {
    @ajni.AndroidEvent::Lifecycle(@ajni.Lifecycle::Resumed) => println("resumed")
    @ajni.AndroidEvent::UiTask => println("Android main Looper callback")
    _ => ()
    })

    // Remove the observer before application shutdown.
    @ajni.remove_event_handler(subscription)

    @ajni.post_to_ui() schedules an asynchronous callback on Android's main Looper. @ajni.start_worker() demonstrates a native-owned thread attaching to ART, posting back to the UI thread, then detaching.

    #Android Host

    The Android application links the generated MoonBit native artifact and uses the reusable Kotlin host from the android:host Gradle module. Initialize it once, then forward the Activity lifecycle and attach a caller-owned container on Android's main thread:

    import dev.nanaloveyuki.ajni.host.NativeBridge NativeBridge.initialize(applicationContext) NativeBridge.attachWebViewContainer(container) // During Activity teardown: NativeBridge.detachWebViewContainer(container) NativeBridge.shutdown()

    Use android/app/src/main/cpp/CMakeLists.txt as the integration template. It generates the MoonBit Android host, compiles the MoonBit runtime, and links libandroid and liblog. The configured minimum Android API is 24; supported demo ABIs are arm64-v8a and x86_64.

    #WebView Feature

    The WebView host must be attached before @webview.create. Commands are queued on Android's main Looper when called from another thread. Each view has a caller-provided Int64 handle.

    import {
    "Nanaloveyuki/ajni/webview",
    }

    let subscription = @webview.install_event_handler(event => match event.kind {
    @webview.EventKind::Created(_) => println("ready")
    @webview.EventKind::ScriptResult(request_id, json) =>
    println("\{request_id}: \{json}")
    @webview.EventKind::PageMessage(body, origin, _is_main_frame) =>
    println("\{origin}: \{body}")
    @webview.EventKind::AssetRequest(request) => println(request.path)
    @webview.EventKind::OperationFailed(operation_id, message) =>
    println("\{operation_id}: \{message}")
    _ => ()
    })

    try! @webview.create(
    1L,
    "https://app.example.test",
    @webview.InitialContent::Url("https://app.example.test/assets/index.html"),
    document_start_scripts=["globalThis.appReady = true"],
    operation_id="create-browser",
    )
    try! @webview.eval(1L, "document.title", "title-request")
    try! @webview.destroy(1L, operation_id="destroy-browser")
    @webview.remove_event_handler(subscription)

    Importing only the core package does not compile src/webview/ajni_webview_bridge.c. An Android build that imports ajni/webview must also include that stub, define AJNI_FEATURE_WEBVIEW=1, and export ajni_dispatch_webview_event; the bundled CMake template demonstrates all three requirements.

    The host enables JavaScript for eval, disables file and content access, disables mixed content and multiple windows, enables Safe Browsing on Android 8+, and does not expose addJavascriptInterface. Web messages are delivered only through AndroidX WebKit's trusted-origin listener. Embedded resources use the same origin's /assets/ path and emit AssetRequest; complete them with respond_asset before the configured timeout.

    #Build And Verify

    Host-side checks:

    moon fmt --check moon check --target native moon test --target native -v

    For an Android build, install Android SDK platform tools, NDK 29.0.14206865, CMake, Java 17, Gradle, and MoonBit. The bundled demo can run its emulator tests with:

    $env:ANDROID_SDK_ROOT = "C:\path\to\Android\Sdk" $env:ANDROID_NDK_HOME = "C:\path\to\android-ndk-r29" $env:ANDROID_SERIAL = "emulator-5554" gradle -p android :app:connectedDebugAndroidTest

    The GitHub workflow builds the Android demo for both configured ABIs. Device and emulator validation remain appropriate for changes that alter Android UI or WebView behavior.

    #Contributing

    See CONTRIBUTING.md for feature boundaries, validation, and pull request requirements.

    #ajni Core

    Nanaloveyuki/ajni is the Android JNI runtime package. It exposes lifecycle, surface, worker, and Android main-Looper callbacks without importing the optional WebView bridge.

    #Runtime Events

    ///|
    test {
    let id = install_event_handler(_event => ())
    remove_event_handler(id)
    }

    The Kotlin host invokes native callbacks only after dev.nanaloveyuki.ajni.host.NativeBridge.initialize(...). Use post_to_ui() for an asynchronous main-Looper callback and start_worker() for a native-owned thread that attaches to ART.

    #Optional Browser Support

    Browser support is deliberately outside this package. Import Nanaloveyuki/ajni/webview only when the Android application embeds a WebView; its package documentation describes the command and event contract.

    JniError

    pub(all) suberror JniError {
    NotInitialized
    RuntimeDestroyed
    NativeFailure(String)
    JavaException(String)
    } derive(
    Debug
    )

    JNI failures are represented as values at the MoonBit boundary. The C bridge clears a captured Java exception before returning this error.

    AndroidEvent

    pub(all) enum AndroidEvent {
    Lifecycle(Lifecycle)
    SurfaceCreated(Int, Int)
    SurfaceChanged(Int, Int)
    SurfaceDestroyed
    WorkerAttached
    UiTask
    } derive(Eq,
    Debug
    )

    Events delivered from the Android bridge. Every event handler runs on the Android main Looper; worker-originated events are first posted there by the JNI bridge.

    GlobalRef

    pub struct GlobalRef {
    // private fields
    } derive(Eq,
    Debug
    )

    A Java object retained past the JNI call that created it.

    The raw handle is private so a local reference cannot be accidentally retained as a GlobalRef. Creation and destruction are owned by the C bridge and are always paired with NewGlobalRef/DeleteGlobalRef.

    GlobalRef::from_raw_for_bridge

    fn GlobalRef::from_raw_for_bridge(raw : UInt64) -> GlobalRef

    Creates a wrapper for a NewGlobalRef result owned by the native bridge. Application code should receive these from a bridge API rather than creating one from a raw handle.

    GlobalRef::is_null

    fn GlobalRef::is_null(self : GlobalRef) -> Bool

    Lifecycle

    pub(all) enum Lifecycle {
    Created
    Started
    Resumed
    Paused
    Stopped
    Destroyed
    } derive(Eq,
    Debug
    )

    Android lifecycle values forwarded by the Kotlin bridge.

    LocalFrame

    pub struct LocalFrame {
    // private fields
    } derive(Eq,
    Debug
    )

    A local-reference frame. It is a scope token only: callers must not retain object handles created inside a frame after the associated callback returns.

    LocalFrame::new

    fn LocalFrame::new(capacity? : Int) -> LocalFrame

    decode_utf8

    fn decode_utf8(bytes : BytesView) -> String

    Decodes UTF-8 received from native code. Invalid sequences, including a replacement emitted for isolated Java UTF-16 surrogates, are lossily normalised instead of allowing invalid text into the public API.

    dispatch_from_android

    fn dispatch_from_android(kind : Int, first : Int, second : Int) -> Unit

    Stable C export used by the Android JNI bridge. Applications embedding the MoonBit native artifact link this symbol as ajni_dispatch_event; callers must still install their own event handler to observe the event payload.

    emit_for_test

    fn emit_for_test(kind : Int, first : Int, second : Int) -> Unit

    Emits a bridge event for host-side tests and integration harnesses.

    encode_utf8

    fn encode_utf8(text : String) -> Bytes

    install_event_handler

    fn install_event_handler(handler : (AndroidEvent) -> Unit) -> Int

    Registers a process-wide Android event observer and returns its removal token. Register before Kotlin calls NativeBridge.initialize.

    post_to_ui

    fn post_to_ui() -> Unit raise JniError

    Requests a callback on Android's main Looper. The callback is asynchronous even if the caller is already on the UI thread.

    remove_event_handler

    fn remove_event_handler(id : Int) -> Unit

    runtime_ready

    fn runtime_ready() -> Bool

    start_worker

    fn start_worker() -> Unit raise JniError

    Starts a native-owned worker thread. The bridge attaches it to the VM, then posts WorkerAttached and UiTask to the Android main Looper before detaching it.