Android 学习之旅—面对“The number of method references in a .dex file cannot exceed 64K”

mac2026-06-13  0

报错说明

Error:The number of method references in a .dex file cannot exceed 64K. Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html Error:Execution failed for task ‘:xxx:transformClassesWithDexForDebug’. com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: java.lang.UnsupportedOperationException

产生原因

上面的错误显示一个共同的数字:65536。这个数字是重要的,它代表了引用的总数,可以在单个调用的代码Dalvik可执行(Dex)字节码文件。如果你的Android应用发生这个错误,恭喜你,你的代码已经达到了一定的量. Android应用程序(APK)在Dalvik可执行文件的形式包含可执行的字节码文件(DEX)文件,其中包含已编译的代码来运行你的应用程序。Dalvik可执行规格限制一个Dex文件包含65536个方法:包括Android框架方法、Library方法的总数、和你自己的代码方法总数。因为65536等于64×1024,这一限制被称为“64k引用限制”。 这个极限就要求我们配置应用程序的构建过程,需要生成多个DEX文件,所以称为multidex 配置。

以上的说明来自链接,详细的细节我也不是很清楚,留作以后学习

解决方法

在这里,我们需要更改gradle文件(module和project的都要更改)

第一步

修改project的gradle配置: 在buildscript中的仓库中添加:

maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/' } maven{ url 'http://maven.aliyun.com/nexus/content/repositories/jcenter'}

在allprojects中的仓库中添加:

maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/' } maven{ url 'http://maven.aliyun.com/nexus/content/repositories/jcenter'}

添加之后project的gradle文件显示如下:

buildscript { repositories { //这里是你自己的添加的链接 maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/' } maven{ url 'http://maven.aliyun.com/nexus/content/repositories/jcenter'} } dependencies { classpath 'com.android.tools.build:gradle:3.3.2' } } allprojects { repositories { //这里是你自己的添加的链接 maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' } maven { url 'http://maven.aliyun.com/nexus/content/repositories/jcenter'} } }

以上的步骤相当于把阿里云的仓库取出来,放入自己的项目中。有的时候可以不需要阿里云,但是一开始在没有把阿里云的镜像maven库导入的时候sync一直失败…(明明我也搭梯子了的说)

第二步

修改module的gradle配置: 在defaultConfig中添加

multiDexEnabled true

在dependencies中添加

implementation 'com.android.support:multidex:1.0.1'

第三步

sync整个项目即可

第四步(可选)

大部分其他的教程都说要修改manifest文件Application的配置,这一步我没有实现但是我的AS也可以跑了 有关这一部分,大家可以参考链接

最新回复(0)