在将 ktor 依赖项用于带有 kotlin 多平台的 commonMain 源集时,我遇到了 Android Studio IDE 的问题。问题是 IDE 无法识别这种依赖关系,但程序编译并运行良好。此外,在 androidMain 源集中,依赖项被识别。我见过其他关于类似问题的问题,但我还没有看到任何人在程序编译和运行时遇到这个问题。
Gradle 依赖项
以下是项目共享文件夹中的build.gradle.kts。
kotlin {
android()
ios {
binaries {
framework {
baseName = "shared"
}
}
}
sourceSets {
val commonMain by getting {
dependencies {
implementation("io.ktor:ktor-client-core:1.5.1")
implementation("io.ktor:ktor-client-cio:1.5.1")
}
}
val androidMain by getting {
dependencies {
implementation("com.google.android.material:material:1.2.1")
implementation("io.ktor:ktor-client-android:1.5.1")
}
}
...
}
}
其中的点表示其他源集的依赖关系,例如 iosMain 是空的。
在 commonMain 代码中,我有一个类 KtorTest:
package com.example.myapplication222.shared
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.request.*
class KtorTest {
val client: HttpClient = HttpClient(CIO)
suspend fun get(): String {
val res: String = client.get("http://www.7timer.info/bin/api.pl?lon=113.17&lat=23.09&product=astro&output=json")
return res
}
}
主要活动
在主要活动中,我导入并使用 KtorTest 类来执行获取请求。
package com.example.myapplication222.androidApp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.myapplication222.shared.KtorTest
import kotlinx.coroutines.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var response = ""
val c = GlobalScope.launch {
response = get()
}
c.invokeOnCompletion {
println("***RESPONSE***");
println(response) }
}
suspend fun get(): String {
val a = KtorTest()
return a.get()
}
}
结果
该程序构建并运行并打印出以下内容。
I/System.out: ***RESPONSE***
{
"product" : "astro" ,
"init" : "2021021700" ,
"dataseries" : [
{
"timepoint" : 3,
"cloudcover" : 4,
I/System.out: "seeing" : 6,
"transparency" : 2,
"lifted_index" : 15,
"rh2m" : 5,
"wind10m" : {
"direction" : "NE",
"speed" : 3
},
"temp2m" : 20,
"prec_type" : "none"
},
...
}
where the response is cut short for brevity
Android Studio 截图:
第一个屏幕截图是上面介绍的 KtorTest。
KtorTest in common Android Studio kotlin 多平台项目中共享代码的主要内容
第二张截图是类KtorTest2,除了位于多平台项目中共享文件夹的androidMain文件夹中外,与上面的KtorTest完全一样。
Android Studio kotlin 多平台项目中共享代码的 androidMain 中的 KtorTest2
在这些图像中,您可以看到 IDE 在 commonMain 中抱怨 ktor,但在 androidMain 中没有。