解决Android方法数超出限定的问题(有关multiDex,jumboMode的解释)

在Android项目中引入过多的jar会出现错误:

android.dex.DexIndexOverflowException: Cannot merge new index xxxx into a non-jumbo instruction!

这个错误出现的原因是 Android设定的方法数是65536个(DEX 64K problem),超过这个方法数,导致dex无法生成,就无法生成APK.

限制原因:早期的Dalvik VM内部使用short类型变量来标识方法的id,就有了 最大方法数的限制65536。

解决方法:

  • 删除不用的方法,删除不使用的jar
    项目维护时间长了,里面会出现不再使用的类和不再使用的方法,建议集中清理下,把不再使用的方法,不再使用的类都清除,这样的好处是代码也干净了,如果方法数超出的不是太多的话通过清理就可以让方法数减少到65536以下,一般来说jar里面的方法数最好,清除一两个无用的jar包就能大大的减少方法数。

  • 分包
    通过在defaultConfig中设置multiDexEnabled可以开启分包模式,分包之后的Dex就低于了限制数,保证了正常的打包。

defaultConfig {
    multiDexEnabled=true
}
  • 忽略方法数限制的检查
android.dexOptions {
    jumboMode = true
}

设置dexOptions的,不做方法数限制的检查,这样做的缺点是apk无法再低版本的设备上面安装,会出现错误:

INSTALL_FAILED_DEXOPT

关于dexoptionsjumboMode在stackoverflow中有一段解释,我翻译一下:

In the standard java world:

  • When you compile standard java code : the compiler produce *.class file. A *.class file contains standard java bytecode that can be executed on a standard JVM.

  • 在标准Java的世界
    当你编译java代码时,编译器生成.class文件。.class文件包含了java的字节码。这些字节码在JVM中执行。

In the Android world:

  • It is different. You use the java language to write your code, but the compiler don't produce *.class files, it produce *.dex file. A *.dex file contains bytecode that can be executed on the Android Virtual Machine (dalvik) and this is not a standard Java Virtual Machine.
    To be clear: a dex file in android is the equivalent of class in standard java.
    So dexoptions is a gradle object where some options to configure this java-code-to-android-bytecode transformation are defined. The options configured via this object are :
    • targetAPILevel
    • force-jumbo mode (when enabled it allows a larger number of strings in the dex files)

在安卓的世界则不同:

  • 你用java语音写安卓的代码,但是编译器生成的是.dex文件,不是.java文件。.dex文件包含了在Android虚拟机中可以执行的字节码,而不是JVM。所以.dex文件的作用和标准Java中的.class文件差不多。
    dexoptions是一个gradle对象,这个对象用来设置从java代码向.dex文件转化的过程中的一些配置选项。其中一个就是force-jumbo mode。force-jumbo mode允许你创建更大的.dex文件。

参考资料:

  1. https://segmentfault.com/a/1190000004187484
  2. https://stackoverflow.com/questions/24224186/what-is-dex-in-gradle/24224385#24224385
  3. http://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.DexOptions.html
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,968评论 25 709
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,745评论 2 45
  • 在媳妇老家又看到了美丽的星空 灌肠真难吃都是面 两个侄子真2
    左右逢石阅读 1,711评论 0 0
  • 序 这是一个关于麻城的系列作品,我所取人 物、环境、故事线索,皆能在这个荒凉的小 镇...
    傅立東阅读 3,707评论 1 1
  • 两年后回来写续集,顺便改了标题 2016.3.28 分手第一天去跑了15公里,接着又马不停蹄练了1个小时hiit....
    hffbnkkhnm阅读 4,563评论 0 0

友情链接更多精彩内容