Android Kotlin Backend
Relevant source files
The following files were used as context for generating this wiki page:
The Android Kotlin Backend serves as the bridge between the Tauri framework (Rust/JavaScript) and the Android USB Host API. It enables mobile applications to communicate with serial devices over USB by wrapping the usb-serial-for-android library. This backend is responsible for device discovery, port configuration, lifecycle management, and efficient data streaming through a batched emission system.
Sources: android/README.md:5-7, android/src/main/kotlin/app/tauri/serialplugin/SerialPlugin.kt:92-105
Architecture Overview
The backend is structured into two primary functional layers: the Plugin Interface and the Port Management layer. The SerialPlugin class handles the communication with Tauri's IPC, parsing arguments from the frontend, and triggering events back to the webview. The SerialPortManager acts as the engine, handling the low-level USB connection details and hardware-specific configurations.
Core Components
| Component | Description |
|---|---|
SerialPlugin | The main entry point annotated with @TauriPlugin. It maps JS commands to Kotlin functions and manages the activity lifecycle to prevent memory leaks. |
SerialPortManager | Manages the collection of active UsbSerialPort instances. It handles the actual opening, closing, reading, and writing operations. |
BufferedEmitter | A specialized component used during listening operations to coalesce incoming bytes into batches before emitting them as serialData events. |
SerialPortConfig | A data class containing port parameters such as baud rate, data bits, parity, stop bits, and flow control. |
Sources: android/src/main/kotlin/app/tauri/serialplugin/SerialPlugin.kt:85-88, android/BUILD_INSTRUCTIONS.md:61-68, CHANGELOG.md:15-18
System Relationships
The following diagram illustrates the relationship between the Android Activity, the Serial Plugin, and the hardware-level Port Manager.
Command Implementation
The backend exposes several commands via the @Command annotation. These functions parse incoming Invoke objects into typed arguments using helper classes like PortConfigArgs and WriteArgs.
Port Configuration Handling
The backend features enhanced type flexibility, allowing configuration parameters (DataBits, Parity, StopBits, FlowControl) to be passed as either String identifiers or Number values. This is achieved through companion object helpers and fromValue methods within the enum classes.
val dataBits = when (args.dataBits) {
is String -> DataBits.valueOf(args.dataBits as String)
is Number -> DataBits.fromValue((args.dataBits as Number).toInt())
null -> DataBits.EIGHT
else -> throw IllegalArgumentException("Invalid data bits type")
}
Sources: android/src/main/kotlin/app/tauri/serialplugin/SerialPlugin.kt:151-177, debug.md:12-14
Available Commands Table
| Command | Args Type | Description |
|---|---|---|
availablePorts | N/A | Returns a map of all detected USB devices and their port information. |
open | PortConfigArgs | Initializes and opens a connection to a specific device path. |
write | WriteArgs | Sends string-based data to an open port. |
writeBinary | WriteBinaryArgs | Sends raw bytes to an open port. |
startListening | StartListenArgs | Begins a background thread to monitor incoming data with a configurable flush interval. |
Sources: android/src/main/kotlin/app/tauri/serialplugin/SerialPlugin.kt:127-310
Data Flow and Listening
The listening mechanism is designed for high-performance data transfer. When startListening is invoked, the SerialPortManager starts a background task. Incoming data is passed through a SerialByteAccumulator and then a BufferedEmitter.
Batched Emission Logic
Incoming data is not emitted byte-by-byte to the webview. Instead, it is coalesced based on a serialDataFlushIntervalMs (clamped between 10ms and 2000ms). This prevents the IPC bridge from being overwhelmed by high-frequency updates.
Lifecycle and Resource Management
To prevent stale native work and memory leaks, the SerialPlugin registers Application.ActivityLifecycleCallbacks during its load() phase.
- Activity Destruction: When the host Activity is destroyed, the plugin automatically calls
serialPortManager.cleanup(). - Cleanup Actions: This process closes all open USB ports, unregisters the broadcast receiver used for USB permissions, and shuts down the IO executor.
- Manual Cleanup: Commands like
closeAllandforceCloseare also available for explicit resource management from the frontend.
Sources: android/src/main/kotlin/app/tauri/serialplugin/SerialPlugin.kt:113-134, android/README.md:10-12
Data Conversion Helpers
Because Tauri requires data to be passed as JSObject or JSArray, the backend includes extension functions to convert Kotlin collections. This is particularly important for the availablePorts command, which returns complex nested maps of port properties.
Map<String, Any?>.toJSObject(): Recursively converts maps.List<Any?>.toJSArray(): Converts lists of primitives or nested maps/lists.
Sources: android/src/main/kotlin/app/tauri/serialplugin/SerialPlugin.kt:23-64, android/src/test/kotlin/app/tauri/serialplugin/SerialPluginConversionTest.kt:13-60
Summary
The Android Kotlin Backend provides a robust, lifecycle-aware implementation for serial communication. By utilizing a batched emission strategy via the BufferedEmitter and providing flexible type handling for port configurations, it ensures efficient and reliable interaction with USB hardware on Android devices within the Tauri ecosystem.