首页 > 解决方案 > 如何修复 Android .aar 项目中的“java.lang.NoClassDefFoundError”

问题描述

我有一个.aar构建的 android 库,我正在尝试将它与其中一个项目集成。当应用程序尝试打开.aar我使用改造进行 API 调用的库的初始屏幕时。我收到以下异常

java.lang.NoClassDefFoundError:解析失败:Lokhttp3/OkHttpClient$Builder;

我没有在我的.aar项目中混淆或启用 pro-guard。

以下是我的.aarGradle 依赖项

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'

标签: androidretrofit2okhttp3aar

解决方案


好的,这是一个常见的问题。有几种方法可以在其他项目中使用 android 库(aar)。例如:

  1. 通过将此 aar 作为模块导入示例项目,使用 implementation project(':mylibrary').
  2. 通过将您的 aar 上传到 maven 存储库(artifactory、maven local、Jitpack 等)

注意这一点:

  1. 如果您使用上面的数字 1,那么您还必须使用相同版本将(retrofit、okhttp3 等)添加到您的示例项目中,因为默认情况下 aar 不包含子依赖项。这就是为什么你会得到那个异常“java.lang.NoClassDefFoundError: Failed resolution of: Lokhttp3/OkHttpClient$Builder'”。
  2. 如果您使用上面的数字 2,那么您必须确保您的 pom.xml 文件包含您的子依赖项,因为服务器需要下载并在您的示例项目中提供它们。

我推荐什么?

我建议开发人员使用MavenLocal(),它会在将 aar 发布到 Jitpack 之类的公共存储库或您想要的任何东西之前复制一个真实场景。

我该怎么做?

  1. 在你的库模块的 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)
                    }
                }
            }
        }
    }
}

运行assemblepublishToMavenLocal分级任务。你会看到这样的东西: 在此处输入图像描述

  1. 在您的示例项目中
allprojects {
    repositories {
        mavenLocal()
        ...
    }
}

implementation '${YOUR_GROUP_ID}:${YOUR_ARTIFACT_ID}:${YOUR_VERSION}'


推荐阅读