Android开发Error之 The number of method references in a .dex file cannot exceed 64K

在遇到这个报错前我并不知道 Android app里面的方法数是有限制的,这里说明一下,Android 平台的 Java 虚拟机 Dalvik 执行 Dex 程序时,使用的是 short 类型来索引 DEX 文件中的方法。这就意味着单个 Dex 文件可被引用的方法总数被限制为64x1024, 即65536。其中包括:

  • Android Framework的方法
  • library的方法
  • 我们自己写的方法

去除重复包

我们在项目中常常都会用到 Library,然而 Library 的 build.gradle 和我们 app 的 build.gradle 引用了相同类型不同版本的包时就会有重复的包,下面上张图,方便理解。


项目包重复

其中的 v4 包和 annotations 包引用了两个不同的版本,增加方法数量的同时也增加了 .apk 文件的大小,一般出现 The number of method references in a .dex file cannot exceed 64K 报错时,先看 External Libraries 里面是否有大量的重复包,若有,将版本都设置成一致的基本能解决这个异常。若问题任然存在,可能是项目本身就比较大,也大量的使用了第三方框架等等。

分割 Dex 文件解决方法限制

打开app的 build.gradle

  1. 在dependencies 中添加
compile 'com.android.support:multidex:1.0.1'
  1. 在 defaultConfig 中添加
multiDexEnabled true

如:

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.3'

    defaultConfig {
        applicationId "XXXXXX"
        ......
        multiDexEnabled true
    }
    buildType {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    .......
    'com.android.support: multidex:1.0.1'
}
  1. 在 AndroidManifest.xml 中的 application 标签中添加


      
        ...
     
 

或者如果你的工程中已经含有 Application 类,那么让它继承 MultiDexApplication 类

public class App extends MultiDexApplication {
...
}

如果你的Application已经继承了其他类并且不想做改动,那么还有另外一种使用方式:重写attachBaseContext() 方法

@Override
 protected void attachBaseContext(Context base) {  
     super.attachBaseContext(base);   
      MultiDex.install(this) ;
}

参考文章
Android应用使用Multidex突破64K方法数限制
Android 出现 java.lang.NoClassDefFoundError错误的一种解决方案
Android开发 Error:The number of method references in a .dex file cannot exceed ...

你可能感兴趣的:(Android开发Error之 The number of method references in a .dex file cannot exceed 64K)