android - 如何修复 Android .aar 项目中的“java.lang.NoClassDefFoundError”
问题描述
我有一个.aar
构建的 android 库,我正在尝试将它与其中一个项目集成。当应用程序尝试打开.aar
我使用改造进行 API 调用的库的初始屏幕时。我收到以下异常
java.lang.NoClassDefFoundError:解析失败:Lokhttp3/OkHttpClient$Builder;
我没有在我的.aar
项目中混淆或启用 pro-guard。
以下是我的.aar
Gradle 依赖项
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:converter-gson:2.2.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'
解决方案
好的,这是一个常见的问题。有几种方法可以在其他项目中使用 android 库(aar)。例如:
- 通过将此 aar 作为模块导入示例项目,使用
implementation project(':mylibrary')
. - 通过将您的 aar 上传到 maven 存储库(artifactory、maven local、Jitpack 等)
注意这一点:
- 如果您使用上面的数字 1,那么您还必须使用相同版本将(retrofit、okhttp3 等)添加到您的示例项目中,因为默认情况下 aar 不包含子依赖项。这就是为什么你会得到那个异常“java.lang.NoClassDefFoundError: Failed resolution of: Lokhttp3/OkHttpClient$Builder'”。
- 如果您使用上面的数字 2,那么您必须确保您的 pom.xml 文件包含您的子依赖项,因为服务器需要下载并在您的示例项目中提供它们。
我推荐什么?
我建议开发人员使用MavenLocal()
,它会在将 aar 发布到 Jitpack 之类的公共存储库或您想要的任何东西之前复制一个真实场景。
我该怎么做?
- 在你的库模块的 build.gradle 里面:
apply plugin: 'maven-publish'
project.afterEvaluate {
publishing {
publications {
library(MavenPublication) {
setGroupId 'YOUR_GROUP_ID'
//You can either define these here or get them from project conf elsewhere
setArtifactId 'YOUR_ARTIFACT_ID'
version android.defaultConfig.versionName
artifact bundleReleaseAar //aar artifact you want to publish
pom.withXml {
def dependenciesNode = asNode().appendNode('dependencies')
configurations.implementation.allDependencies.each {
def dependencyNode = dependenciesNode.appendNode('dependency')
dependencyNode.appendNode('groupId', it.group)
dependencyNode.appendNode('artifactId', it.name)
dependencyNode.appendNode('version', it.version)
}
}
}
}
}
}
运行assemble
和publishToMavenLocal
分级任务。你会看到这样的东西:
- 在您的示例项目中
allprojects {
repositories {
mavenLocal()
...
}
}
implementation '${YOUR_GROUP_ID}:${YOUR_ARTIFACT_ID}:${YOUR_VERSION}'
推荐阅读
- android - 通过“SDK Manager”安装 Android Emulator 时出错,也无法手动安装
- reactjs - 在 React Native Expo 中打开相机
- apache-flink - flink 1.12.1 示例应用程序在单节点纱线集群上失败
- javascript - 慢慢改变背景颜色
- python - 导入多个具有相似名称的 excel 文件,旋转每个 excel 文件,然后将结果附加到单个文件中
- r - 组合数据帧的行,其中每一行都是 df 本身
- php - Woocommerce:特定产品的强制性优惠券
- routes - 如何在 Sylius 中禁用 API 的管理部分?
- python - 将excel电子表格转换为json
- google-apps-script - 尽管填写了被调用函数,但函数调用未返回变量值