将现有Android Java项目迁移至KMM后出现大量未解析引用错误求助
问题描述
要把现有Android应用通过Kotlin Multiplatform(KMM)适配iOS,完全零基础。创建shared模块并调整build配置后项目能构建,但把AndroidApp模块的Java文件移到shared模块转成Kotlin后,所有Android相关导入和代码都报未解析引用错误,比如android.content.Intent、FirebaseInstanceId、getApplicationContext()等都识别不了。
转换后的Kotlin代码
package eu.tinysolutions.tinyprocas import android.content.Intent import android.util.Log import com.google.firebase.iid.FirebaseInstanceId import com.google.firebase.iid.FirebaseInstanceIdService class FbInstanceIdService : FirebaseInstanceIdService() { fun onTokenRefresh() { // Get updated InstanceID token. val refreshedToken: String = FirebaseInstanceId.getInstance().getToken() android.util.Log.d( TAG, "Refreshed token: $refreshedToken" ) // If you want to send messages to this application instance or // manage this apps subscriptions on the server side, send the // Instance ID token to your app server. getApplicationContext().sendBroadcast(Intent(TOKEN_BROADCAST)) storeToken(refreshedToken) } private fun storeToken(token: String) { SharedPreferencesManager.getInstance(getApplicationContext()).storeFirebaseToken(token) } companion object { const val TAG = "FirebaseID" const val TOKEN_BROADCAST = "tokenbroadcast" } }
报错信息
- Unresolved reference: content
- Unresolved reference: util
- Unresolved reference: FirebaseInstanceId
- Unresolved reference: FirebaseInstanceIdService
- Unresolved reference: getApplicationContext
项目级build.gradle文件
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() jcenter() mavenCentral() } dependencies { classpath('com.android.tools.build:gradle:8.1.4') classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.0" classpath 'com.google.gms:google-services:4.4.1' } } plugins { // Declare the Kotlin Multiplatform plugin with a specific version and set apply false id 'org.jetbrains.kotlin.multiplatform' version '1.9.0' apply false id 'com.android.application' version '8.1.4' apply false id 'com.android.library' version '8.1.4' apply false id("com.google.gms.google-services") version "4.4.1" apply false } allprojects { repositories { google() jcenter() mavenCentral() } } task clean(type: Delete) { delete rootProject.buildDir }
androidApp模块build.gradle文件
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' android { compileSdk 27 defaultConfig { applicationId "changedID" minSdkVersion 26 targetSdkVersion 27 versionCode 11 versionName "1.11" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } applicationVariants.all { variant -> variant.resValue "string", "versionName", variant.versionName } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } namespace 'changedNamespace' } repositories { maven { url 'https://jitpack.io' } } dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support.constraint:constraint-layout:1.1.1' implementation 'com.android.support:support-v4:27.1.1' implementation 'com.google.firebase:firebase-messaging:11.8.0' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'com.android.support:support-v4:27.1.1' implementation 'com.android.support:design:27.1.1' implementation 'com.android.volley:volley:1.1.0' implementation 'com.ms-square:expandableTextView:0.1.4' implementation project(':shared') implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3' } apply plugin: 'com.google.gms.google-services'
shared模块build.gradle.kts文件
plugins { //alias(libs.plugins.kotlinMultiplatform) //alias(libs.plugins.androidLibrary) //alias(libs.plugins.androidApplication) id("org.jetbrains.kotlin.multiplatform") id("com.android.application") id("com.google.gms.google-services") } repositories { maven(url = "https://jitpack.io") } kotlin { androidTarget { compilations.all { kotlinOptions { jvmTarget = "1.8" } } } listOf( iosX64(), iosArm64(), iosSimulatorArm64() ).forEach { it.binaries.framework { baseName = "shared" isStatic = true } } sourceSets { val commonMain by getting { dependencies { implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar")))) implementation(project(":shared")) implementation ("com.android.support:appcompat-v7:27.1.1") implementation ("com.android.support.constraint:constraint-layout:1.1.1") implementation ("com.android.support:support-v4:27.1.1") implementation ("com.google.firebase:firebase-messaging:11.8.0") implementation ("com.android.support:support-v4:27.1.1") implementation ("com.android.support:design:27.1.1") implementation ("com.android.volley:volley:1.1.0") implementation ("com.ms-square:expandableTextView:0.1.4") implementation ("com.github.PhilJay:MPAndroidChart:v3.0.3") } } val androidMain by getting{ dependencies{ implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar")))) implementation(project(":shared")) implementation ("com.android.support:appcompat-v7:27.1.1") implementation ("com.android.support.constraint:constraint-layout:1.1.1") implementation ("com.android.support:support-v4:27.1.1") implementation ("com.google.firebase:firebase-messaging:11.8.0") implementation ("com.android.support:support-v4:27.1.1") implementation ("com.android.support:design:27.1.1") implementation ("com.android.volley:volley:1.1.0") implementation ("com.ms-square:expandableTextView:0.1.4") implementation ("com.github.PhilJay:MPAndroidChart:v3.0.3") } } val commonTest by getting { dependencies { implementation(kotlin("test-common")) implementation(kotlin("test-annotations-common")) } } // Specific platform configurations val iosX64Main by getting { dependsOn(commonMain) } val iosArm64Main by getting { dependsOn(commonMain) } val iosSimulatorArm64Main by getting { dependsOn(commonMain) } } } android { namespace = "changedNamespace" compileSdk = 27 defaultConfig { minSdk = 26 applicationId = "changedID" versionCode = 11 versionName = "1.11" targetSdk = 27 } }
解决方案
1. 修正shared模块的插件配置
shared模块是KMM跨平台库,不能用com.android.application插件,替换为com.android.library。修改shared模块build.gradle.kts的plugins块:
plugins { id("org.jetbrains.kotlin.multiplatform") id("com.android.library") // 替换原com.android.application id("com.google.gms.google-services") }
同时删除android块中的applicationId(library模块无需该配置):
android { namespace = "changedNamespace" compileSdk = 27 defaultConfig { minSdk = 26 // 移除applicationId = "changedID" versionCode = 11 versionName = "1.11" targetSdk = 27 } }
2. 调整代码存放位置
FbInstanceIdService是Android平台专属代码(依赖Android SDK和Firebase Android库),必须从commonMain目录移到shared/src/androidMain/kotlin/[你的包名]目录下。
3. 精简依赖配置
- 移除commonMain中所有Android专属依赖(如com.android.support、com.google.firebase:firebase-messaging等),这些依赖只保留在androidMain中。
- 删除
implementation(project(":shared")),避免循环依赖。 - 精简后的sourceSets配置:
sourceSets { val commonMain by getting { dependencies { // 仅保留跨平台通用依赖,如kotlin标准库 } } val androidMain by getting{ dependencies{ implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar")))) implementation("com.android.support:appcompat-v7:27.1.1") implementation("com.android.support.constraint:constraint-layout:1.1.1") implementation("com.android.support:support-v4:27.1.1") implementation("com.google.firebase:firebase-messaging:11.8.0") implementation("com.android.support:design:27.1.1") implementation("com.android.volley:volley:1.1.0") implementation("com.ms-square:expandableTextView:0.1.4") implementation("com.github.PhilJay:MPAndroidChart:v3.0.3") } } val commonTest by getting { dependencies { implementation(kotlin("test-common")) implementation(kotlin("test-annotations-common")) } } // iOS相关sourceSet默认依赖commonMain,无需手动声明dependsOn val iosX64Main by getting val iosArm64Main by getting val iosSimulatorArm64Main by getting }
4. 修正Kotlin代码问题
onTokenRefresh是重写父类方法,必须添加override关键字。- 移除冗余的
android.util.Log调用,直接使用导入的Log。
修正后的代码:
package eu.tinysolutions.tinyprocas import android.content.Intent import android.util.Log import com.google.firebase.iid.FirebaseInstanceId import com.google.firebase.iid.FirebaseInstanceIdService class FbInstanceIdService : FirebaseInstanceIdService() { override fun onTokenRefresh() { val refreshedToken: String = FirebaseInstanceId.getInstance().getToken() Log.d(TAG, "Refreshed token: $refreshedToken") getApplicationContext().sendBroadcast(Intent(TOKEN_BROADCAST)) storeToken(refreshedToken) } private fun storeToken(token: String) { SharedPreferencesManager.getInstance(getApplicationContext()).storeFirebaseToken(token) } companion object { const val TAG = "FirebaseID" const val TOKEN_BROADCAST = "tokenbroadcast" } }
5. 同步并重构项目
点击Android Studio的Sync Project with Gradle Files按钮,执行Clean Project和Rebuild Project,错误即可解决。
内容的提问来源于stack exchange,提问作者cheese
相关产品推荐
相关产品推荐

