Android方法数超出限定的问题(multiDex,jumboMode)
16lz
2022-06-03
在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。
-
分包
通过在defaultConfig中设置multiDexEnabled开启分包模式,分包之后的Dex就低于了限制数,保证了正常的打包。
1 defaultConfig {2 multiDexEnabled=true3 }
- 忽略方法数限制的检查
1 android.dexOptions {2 jumboMode = true3 }
设置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.
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的世界
当编译java代码时,编译器生成.class
文件。.class
文件包含了java的字节码。这些字节码在JVM中执行。
在安卓的世界则不同:
- 用java语音写安卓的代码,但是编译器生成的是
.dex
文件,不是.java
文件。.dex
文件包含了在Android虚拟机中可以执行的字节码,而不是JVM。所以.dex
文件的作用和标准Java中的.class文件差不多。
dexoptions
是一个gradle对象,这个对象用来设置从java代码向.dex文件转化的过程中的一些配置选项。其中一个就是force-jumbo mode。force-jumbo mode允许你创建更大的.dex
文件。
参考资料:
- https://segmentfault.com/a/1190000004187484
- https://stackoverflow.com/questions/24224186/what-is-dex-in-gradle/24224385#24224385
- http://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.DexOptions.html
更多相关文章
- android通过chmod命令实现文件权限修改
- Android下PreferenceScreen 加载流程
- Android读写文件
- android应用 小试牛刀 开发自己的应用程序就是这么简单
- Android原生方法和Web JS互相调用-两种写法
- 浅谈Java中Collections.sort对List排序的两种方法
- NPM 和webpack 的基础使用
- Python list sort方法的具体使用
- 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程