zoukankan      html  css  js  c++  java
  • 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。

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

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

    设置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.

    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的世界
      当编译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文件。

    参考资料:

    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
  • 相关阅读:
    Kubernetes之network: failed to set bridge addr: "cni0" already has an IP address different from xxx问题
    k8s的存储Volume
    系统漏洞扫描与分析软件
    linux图形化安装oracle
    JMX监控tomcat jdbc pool
    Hyper-V
    苹果手机
    读书
    clickhouse count
    clickhouse分布式表
  • 原文地址:https://www.cnblogs.com/linghu-java/p/10983671.html
Copyright © 2011-2022 走看看