我正在为 Android 和 iOS 构建一个多平台库。我的 gradle 文件如下所示:
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.4.0'
}
repositories {
mavenCentral()
}
group 'com.example'
version '0.0.1'
apply plugin: 'maven-publish'
kotlin {
jvm()
// This is for iPhone simulator
// Switch here to iosArm64 (or iosArm32) to build library for iPhone device
ios {
binaries {
framework()
}
}
sourceSets {
commonMain {
dependencies {
implementation kotlin('stdlib-common')
implementation("com.ionspin.kotlin:bignum:0.2.2")
}
}
commonTest {
dependencies {
implementation kotlin('test-common')
implementation kotlin('test-annotations-common')
}
}
jvmMain {
dependencies {
implementation("com.ionspin.kotlin:bignum:0.2.2")
}
}
jvmTest {
dependencies {
implementation kotlin('test')
implementation kotlin('test-junit')
}
}
iosMain {
}
iosTest {
}
}
}
configurations {
compileClasspath
}
我正在使用第三方库,我正在像这样使用它:fun test(value: String): Int {
return BigDecimal.parseString(value).toBigInteger().intValue()
}
问题是当我构建 .jar 时,不包含 bignum 库,当我在 Android 项目中使用该库时,出现异常 ClassNotFoundException: 找不到类“com.ionspin.kotlin.bignum.decimal.BigDecimal ”。有没有办法在 Android 的 .jar 和 iOS 的 .framework 中包含第三方库?
最佳答案
虚拟机
所以,我发现生成 的唯一方法 fat jar 子 像您期望的那样工作是通过在 project:build.gradle.kts
中添加两个自定义 gradle 任务应用 后的 KMP 库 java 插入。
plugins {
[...]
id("java")
}
[...]
kotlin {
jvm {
[...]
compilations {
val main = getByName("main")
tasks {
register<Copy>("unzip") {
group = "library"
val targetDir = File(buildDir, "3rd-libs")
project.delete(files(targetDir))
main.compileDependencyFiles.forEach {
println(it)
if (it.path.contains("com.")) {
from(zipTree(it))
into(targetDir)
}
}
}
register<Jar>("fatJar") {
group = "library"
manifest {
attributes["Implementation-Title"] = "Fat Jar"
attributes["Implementation-Version"] = archiveVersion
}
archiveBaseName.set("${project.name}-fat")
val thirdLibsDir = File(buildDir, "3rd-libs")
from(main.output.classesDirs, thirdLibsDir)
with(jar.get() as CopySpec)
}
}
tasks.getByName("fatJar").dependsOn("unzip")
}
}
[...]
}
然后您必须启动 fatJar
gradle 任务生成一个 .jar 文件,其中第三个库类从它们相应的 jar 文件中提取。您可以更多地自定义两个自定义 gradle 脚本,以更好地满足您的需求(这里我只包括 com. 包名起始 deps)。
然后在您的 Android 应用程序中
app:build.gradle
文件,您可以像以前一样使用它或简单地使用它implementation files('libs/KMLibraryTest001-fat-1.0-SNAPSHOT.jar')
iOS 当您还要求标题中的 iOS 部分时(即使它是您问题主题中的第二个公民),您只需要使用
api
而不是 implementation
用于您的 3rd 方库以及框架的导出选项。ios() {
binaries {
framework() {
transitiveExport = true // all libraries
//export(project(":LibA")) // this library project in a trainsitive way
//export("your 3rd party lib") // this 3rd party lib in a transitive way
}
}
}
您可以找到完整的引用资料 here .
关于android - Kotlin Native 编译 jar 和框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65039841/