
1. 跨平台SDK开发的技术选型背景在移动互联网快速迭代的今天开发者经常面临一个现实困境如何高效地为不同操作系统平台提供功能一致的SDK传统模式下我们需要为Android和HarmonyOS分别维护两套代码库这不仅造成开发资源浪费更导致功能迭代不同步、问题修复延迟等痛点。Kotlin MultiplatformKMP的出现为这个问题提供了新的解题思路。作为JetBrains推出的跨平台解决方案KMP允许开发者用Kotlin编写核心业务逻辑然后编译生成各平台原生代码。实测数据显示采用KMP后代码复用率可达70%-85%特别适合SDK这类需要保持多平台行为一致性的场景。选择KMP而非Flutter或React Native等框架的核心考量在于SDK通常需要深度集成系统能力如蓝牙、传感器等KMP的expect/actual机制能更灵活地处理平台特定API编译产物是标准库文件.aar/.har而非额外运行时引擎对宿主应用体积影响更小与Android现有工具链完美兼容Gradle构建流程无需大改2. 开发环境搭建与项目初始化2.1 基础工具链配置首先需要确保开发环境满足以下要求Android Studio Giraffe以上版本内置KMP模板支持JDK 17K2编译器对Java新特性有更好支持HarmonyOS DevEco Studio 3.1用于鸿蒙侧调试Kotlin 1.9.20稳定版KMP支持在项目的settings.gradle.kts中启用KMP插件pluginManagement { repositories { google() mavenCentral() gradlePluginPortal() } } plugins { id(org.jetbrains.kotlin.multiplatform) version 1.9.20 }2.2 多平台项目结构设计典型的跨平台SDK目录结构应如下sdk-project/ ├── build.gradle.kts ├── settings.gradle.kts ├── shared/ # 公共代码模块 │ ├── src/ │ │ ├── androidMain/ │ │ ├── harmonyMain/ │ │ └── commonMain/ ├── android/ # Android平台适配层 ├── harmony/ # HarmonyOS平台适配层 └── samples/ # 各平台示例代码关键配置点在shared/build.gradle.ktskotlin { androidTarget { compilations.all { kotlinOptions { jvmTarget 11 } } } // HarmonyOS目标配置 val harmonyTarget when (System.getProperty(os.name)) { Mac OS X - macosArm64(harmony) else - linuxX64(harmony) } sourceSets { val commonMain by getting { dependencies { implementation(org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3) } } val androidMain by getting { dependsOn(commonMain) dependencies { implementation(androidx.core:core-ktx:1.12.0) } } val harmonyMain by getting { dependsOn(commonMain) // 鸿蒙特定依赖 } } }3. 核心逻辑的跨平台实现3.1 使用expect/actual统一API假设我们需要实现网络请求功能在commonMain中定义期望接口expect class HttpClient { fun get(url: String): String }Android平台实现androidMainactual class HttpClient actual constructor() { private val client OkHttpClient() actual fun get(url: String): String { val request Request.Builder().url(url).build() return client.newCall(request).execute().body?.string() ?: } }HarmonyOS平台实现harmonyMainactual class HttpClient actual constructor() { actual fun get(url: String): String { val task HttpTask(url) return task.execute().get() } }3.2 异步操作的统一封装针对Android的Coroutine和HarmonyOS的TaskDispatcher差异可以构建统一异步接口// commonMain expect interface Dispatcher { fun dispatch(block: () - Unit) } expect fun createDispatcher(): Dispatcher // androidMain actual interface Dispatcher { actual fun dispatch(block: () - Unit) { CoroutineScope(Dispatchers.IO).launch { block() } } } // harmonyMain actual interface Dispatcher { actual fun dispatch(block: () - Unit) { GlobalTaskDispatcher.getDefaultDispatcher().asyncDispatch(block) } }4. 平台特定能力适配策略4.1 硬件能力抽象层设计对于需要调用平台特有硬件API的场景如蓝牙建议采用分层设计BluetoothManager ├── common: BluetoothController(interface) ├── android: AndroidBluetoothImpl └── harmony: HarmonyBluetoothImpl在commonMain中定义抽象接口interface BluetoothController { fun scanDevices(): ListDevice fun connect(deviceId: String) } expect fun createBluetoothController(): BluetoothController4.2 资源文件的多平台管理UI资源需要特殊处理推荐方案将图标等资源放在各自平台的res目录通过expect/actual暴露资源引用公共字符串定义在commonMain/resources中示例字符串资源定义// commonMain/resources/MR/base.kt object Strings { val connectTimeout Connection timeout } // androidMain/AndroidManifest.xml中引用 android:labelstring/connect_timeout // harmonyMain/resources/zh-CN/strings.json { string: [ { name: connect_timeout, value: 连接超时 } ] }5. 构建与发布流程优化5.1 多平台产物打包配置Android侧输出标准AARandroid { publishing { singleVariant(release) { withSourcesJar() withJavadocJar() } } } afterEvaluate { publishing { publications { createMavenPublication(maven) { groupId com.example artifactId sdk-core version 1.0.0 from(components[release]) } } } }HarmonyOS侧生成HAR包需特殊处理# 在HarmonyOS模块中添加打包任务 task packageHarmony(type: Zip) { from fileTree(build/libs/harmony) archiveFileName sdk-harmony-1.0.0.har destinationDirectory file(build/outputs) }5.2 持续集成方案推荐GitHub Actions配置示例jobs: build: strategy: matrix: os: [ubuntu-latest, macos-latest] steps: - uses: actions/checkoutv3 - uses: actions/setup-javav3 with: distribution: temurin java-version: 17 - name: Build Android run: ./gradlew :shared:assembleAndroidRelease if: matrix.os ubuntu-latest - name: Build HarmonyOS run: ./gradlew :shared:assembleHarmonyRelease if: matrix.os macos-latest - name: Upload artifacts uses: actions/upload-artifactv3 with: path: | **/build/outputs/*.aar **/build/outputs/*.har6. 实际开发中的经验总结6.1 线程模型的坑与解决方案在混合使用Coroutine和HarmonyOS TaskDispatcher时我们遇到过死锁问题。解决方案是在公共模块中明确定义线程约束使用统一的协程上下文传递机制关键操作添加超时检测示例安全调用代码suspend fun T withTimeoutSafe( timeout: Long 5000, block: suspend () - T ): ResultT try { withTimeout(timeout) { Result.success(block()) } } catch (e: Exception) { Result.failure(e) }6.2 性能优化关键指标经过多个版本迭代我们总结出这些优化点初始化时间控制在200ms以内内存占用不超过宿主应用的5%避免在主线程执行超过2ms的操作实测数据对比优化项优化前优化后冷启动时间320ms180ms内存占用8.2MB5.1MB方法数12438926.3 兼容性处理技巧针对不同HarmonyOS版本的API差异推荐采用能力检测模式fun checkFeatureAvailable(feature: String): Boolean { return try { Class.forName(ohos.$feature) true } catch (e: Exception) { false } }在Android Studio中调试鸿蒙代码的小技巧配置远程调试到DevEco Studio使用adb forward tcp:5005 tcp:5005转发调试端口在KMP代码中添加通用日志接口