在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
关于dexoptions
和jumboMode
在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.
Sodexoptions
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
文件。
参考资料: