428 字
2 分钟
安卓SDK封装笔记
安卓SDK封装笔记
Go 项目生成 Android SDK (AAR) 并在 Kotlin 调用
- 安装 gomobile
go install golang.org/x/mobile/cmd/gomobile@latestgo install golang.org/x/mobile/cmd/gobind@latestgomobile init- 安装安卓 NDK r29以上的版本 https://developer.android.com/ndk/downloads?hl=zh-cn
会自动满足16kb对齐的要求
- 生成 AAR
gomobile bind -v -target=android -androidapi 24 -trimpath -ldflags="-s -w -buildid=" -o mylib.aar ./- 封装安卓SDK大致思路
- GO 语言中导出函数的公开接口需要首字母为大写
- 一般只需暴露 Go 项目的启动、停止、重启、日志、生命周期等函数接口即可
- gobind 将 Go 名称直接转换为 Java 方法名,会遵循 Java 命名规范,也就是首字母是小写,调用方需要注意
- 默认会生成一个
多种架构的通用 AAR,里面会包含所有 Go 支持的多种架构,只需在业务端打包时拆分ABI即可
Rust 使用 uniffi 将项目打包为 Android AAR
大致思路
接口声明 → 工具生成绑定 → 标准 NDK 编译 → 打包,避免手写 JNI 胶水代码。
- 原项目代码零修改
- 包装项目只写接口转发,不写业务
- 和 Go
gomobile bind思路完全一致
步骤
-
Rust 侧暴露接口
- 用
#[uniffi::export]宏标注要公开的函数/类型 - 或编写一个 UDL 文件描述接口
- 在
Cargo.toml中设置crate-type = ["cdylib"]并添加uniffi依赖
- 用
-
生成 Kotlin 绑定
- 用
uniffi-bindgen命令行工具 - 根据上一步的接口定义自动生成 Kotlin 调用代码
- 用
-
编译原生 .so
- 使用
cargo-ndk编译出arm64-v8a等架构的.so动态库
- 使用
-
在 Android 项目中集成
- 将生成的 Kotlin 文件和
.so文件放入 Android 项目目录 - 或通过 Gradle 插件实现自动化
- 将生成的 Kotlin 文件和