🚀KMP适配鸿蒙开发实战|从0到1搭建可运行工程

🔥 上一篇我们详解了KMP与鸿蒙整合的核心原理和适配方案,本文聚焦落地实操,从环境搭建、工程配置到代码编写、调试运行,手把手教你搭建一套能同时运行在鸿蒙/Android/iOS的KMP工程

📋 前置说明

本文是《KMP适配鸿蒙开发》系列第二篇,核心目标是帮你完成:

  • ✅ 搭建兼容鸿蒙的KMP工程环境
  • ✅ 配置鸿蒙自定义平台编译参数
  • ✅ 编写跨平台共享代码+鸿蒙专属实现
  • ✅ 鸿蒙工程集成KMP模块并调试运行

👉 系列第一篇回顾:Kotlin Multiplatform (KMP) 鸿蒙开发整合实战|2026最新方案

🔧 一、环境搭建:从0配置兼容环境

1.1 核心工具清单(必装)
工具 版本要求 作用说明
JDK 11+ 鸿蒙/Android/KMP编译基础
Android Studio 2022.3 Giraffe+ KMP工程开发+鸿蒙SDK配置+断点调试
DevEco Studio 3.2+(可选) 鸿蒙UI预览+真机调试
鸿蒙SDK API 9(OpenHarmony 3.2) 鸿蒙平台核心依赖
Kotlin插件 1.9.20 KMP编译核心插件
Gradle 8.2+ 工程构建工具

1.2 鸿蒙SDK配置

1.2.1 下载SDK

打开 Android Studio → File > Settings > Languages & Frameworks > HarmonyOS,选择 OpenHarmony 3.2 / API 9 下载。

1.2.2 配置环境变量
系统 配置步骤
Windows 新建系统变量 OHOS_SDK_HOME,指向SDK根目录
Mac/Linux ~/.zshrc 中添加 export OHOS_SDK_HOME=你的SDK路径
1.2.3 验证配置
echo %OHOS_SDK_HOME%
echo $OHOS_SDK_HOME

1.3 Gradle全局配置

// 项目根目录 build.gradle.kts
buildscript {
    repositories {
        google()
        mavenCentral()
        maven { url = uri("https://repo.huawei.com/repository/maven/") }
    }
    dependencies {
        classpath("com.android.tools.build:gradle:8.2.0")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.20")
        // 【修改】统一为3.2.0.300,与OpenHarmony 3.2匹配
        classpath("com.huawei.ohos:ohos-gradle-plugin:3.2.0.300")
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
        maven { url = uri("https://repo.huawei.com/repository/maven/") }
        maven { url = uri("https://openharmony.gitee.io/ohpm/repository/") }
    }
}

tasks.withType<JavaCompile> {
    sourceCompatibility = JavaVersion.VERSION_11.toString()
    targetCompatibility = JavaVersion.VERSION_11.toString()
}

🛠️ 二、KMP工程核心配置(适配鸿蒙)

2.1 共享模块(shared)完整配置

// shared模块 build.gradle.kts
plugins {
    kotlin("multiplatform") version "1.9.20"
    id("com.android.library")
}

val ohosSdkHome = System.getenv("OHOS_SDK_HOME")
    ?: System.getProperty("OHOS_SDK_HOME")
    ?: throw GradleException("未配置OHOS_SDK_HOME")

// 【修改】固定为API 9路径,保持OpenHarmony 3.2
val ohosSdkJar = File("$ohosSdkHome/platforms/ohos-9/ohos-sdk.jar")
if (!ohosSdkJar.exists()) {
    throw GradleException("鸿蒙SDK文件缺失")
}

kotlin {
    androidTarget {
        compilations.all {
            kotlinOptions {
                jvmTarget = "11"
                freeCompilerArgs = listOf("-Xopt-in=kotlin.RequiresOptIn")
            }
        }
    }

    iosX64()
    iosArm64()
    iosSimulatorArm64()

    // 自定义鸿蒙平台
    val harmonyTarget = targetFromPreset(jvmPreset, "harmony") {
        compilations.all {
            kotlinOptions {
                jvmTarget = "11"
                freeCompilerArgs = listOf(
                    "-Xjvm-default=all",
                    "-opt-in=kotlin.RequiresOptIn",
                    "-Xskip-metadata-version-check"
                )
            }
            compileClasspath += files(ohosSdkJar)
            runtimeClasspath += files(ohosSdkJar)
            compileDependencyFiles = compileDependencyFiles.filter {
                !it.name.contains("android") && !it.name.contains("androidx")
            }
        }
    }

    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation("org.jetbrains.kotlin:kotlin-stdlib-common")
                implementation("io.ktor:ktor-client-core:2.3.5")
                implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
                implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0")
            }
        }

        val commonTest by getting {
            dependencies {
                implementation(kotlin("test"))
            }
        }

        val androidMain by getting {
            dependencies {
                implementation("org.jetbrains.kotlin:kotlin-stdlib")
                implementation("io.ktor:ktor-client-android:2.3.5")
            }
        }

        val iosMain by creating {
            dependsOn(commonMain)
        }

        // 🔥 鸿蒙专属源码集
        val harmonyMain by creating {
            dependsOn(commonMain)
            dependencies {
                implementation(files(ohosSdkJar))
                // 【修改】全部改为3.2.0.300,与OpenHarmony 3.2一致
                implementation("com.huawei.ohos:os:3.2.0.300")
                implementation("com.huawei.ohos:agp:3.2.0.300")
                implementation("com.huawei.ohos:network:3.2.0.300")
                configurations.all {
                    exclude(group = "com.android")
                    exclude(group = "androidx")
                }
            }
            kotlin.srcDir("src/harmonyMain/kotlin")
            resources.srcDir("src/harmonyMain/resources")
        }
    }
}

android {
    namespace = "com.example.kmp_harmony"
    compileSdk = 34
    defaultConfig {
        minSdk = 21
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_11
        targetCompatibility = JavaVersion.VERSION_11
    }
}

// 验证SDK任务
tasks.register("checkOhosSdk") {
    doLast {
        check(ohosSdkJar.exists()) { "❌ 鸿蒙SDK缺失" }
        // 【修改】提示改为OpenHarmony 3.2
        println("✅ 鸿蒙SDK验证通过:OpenHarmony 3.2 (API 9)")
    }
}

tasks.named("build").configure {
    dependsOn("checkOhosSdk")
}

2.2 标准化源码目录结构

shared/
├── src/
│   ├── commonMain/kotlin/       // 跨平台共享代码
│   ├── androidMain/kotlin/      // Android实现
│   ├── iosMain/kotlin/          // iOS实现
│   ├── harmonyMain/kotlin/      // 鸿蒙实现

✍️ 三、代码编写:跨平台+鸿蒙适配

3.1 跨平台共享代码(commonMain)

// Platform.kt
package com.example.kmp_harmony

expect class Platform {
    val platformName: String
    fun showToast(message: String, duration: ToastDuration = ToastDuration.SHORT)
}

enum class ToastDuration { SHORT, LONG }

class SharedRepository {
    fun getPlatformInfo(): String {
        val platform = Platform()
        return "当前运行平台:${platform.platformName}\nKMP版本:1.9.20"
    }

    fun showTip(message: String) {
        Platform().showToast("KMP提示:$message")
    }

    fun processData(data: List<String>): List<String> {
        return data.filter { it.isNotBlank() }
            .map { it.uppercase() }
            .distinct()
            .sorted()
    }
}

3.2 鸿蒙专属实现(harmonyMain)

actual class Platform {
    // 【修改】兜底文案改为OpenHarmony 3.2
    actual val platformName: String by lazy {
        try {
            "HarmonyOS (Stage 模型 / API 9)"
        } catch (e: Exception) {
            "HarmonyOS 3.2 (Stage 模型 / API 9)"
        }
    }

    actual fun showToast(message: String, duration: ToastDuration) {
        // 鸿蒙原生Toast实现
    }
}

📱 四、鸿蒙工程集成KMP模块

4.1 创建鸿蒙工程

DevEco Studio 3.2 → Empty Ability (Stage)

  • SDK:API 9(OpenHarmony 3.2)

4.2 引入shared模块

// settings.gradle
include ':app', ':shared'
project(':shared').projectDir = new File(settingsDir, '../shared')

4.3 app模块build.gradle

ohos {
    // 【修改】保持API 9
    compileSdkVersion 9
    compatibilityVersion 9

    compileOptions {
        sourceCompatibility = 11
        targetCompatibility = 11
    }
}

dependencies {
    implementation project(':shared')
    // 【修改】统一为3.2.0.300
    implementation 'com.huawei.ohos:os:3.2.0.300'
    implementation 'com.huawei.ohos:agp:3.2.0.300'
    implementation 'com.huawei.ohos:common:3.2.0.300'
}

4.4 页面调用KMP

class MainAbilitySlice : AbilitySlice() {
    private lateinit var repository: SharedRepository

    override fun onStart(intent: Intent?) {
        super.onStart(intent)
        setUIContent(ResourceTable.Layout_ability_main)
        repository = SharedRepository()
        // 调用KMP共享逻辑
        val info = repository.getPlatformInfo()
        repository.showTip("KMP 集成鸿蒙成功")
    }
}

🐞 五、常见问题与解决方案

问题 原因 解决方案
ohos-sdk.jar 找不到 环境变量或路径错误 检查 OHOS_SDK_HOME 指向 ohos-sdk 根目录
字节码版本冲突 JVM 版本不统一 全部设为 11
依赖冲突 安卓与鸿蒙包冲突 exclude android、androidx
编译元数据报错 Kotlin与SDK不匹配 添加 -Xskip-metadata-version-check

OpenHarmony 3.2(API 9)底层运行时基于JDK 11构建,它的虚拟机(OHOS Runtime)只兼容:
字节码版本 55(JVM 11)
向下兼容 52(JVM 8),但KMP 编译时会强制校验版本,低版本会触发兼容性报错

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐