The number of method references in a .dex file cannot exceed 64K.(转)

前言

我一直都知道app里面的方法数是有限制的差不多64000,具体的就未曾考证了
在遇到这个问题之前,一直以为这个一个多么遥远的距离
其实并不是的,稍有不慎这个异常出来了
当前并不是你真的有编写了64k的方法数量了
大部分都是因为包的重复导入,当前就算是真的超过64k的方法,本文也将提出解决方案

当出现这个情况别慌,我们一步一步来

去除重复包

我们项目中常常都会用到几个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'

(2)在 defaultConfig 中添加

multiDexEnabled true

比如

android { 
   compileSdkVersion 23  
   buildToolsVersion '23.0.2'   

   defaultConfig { 
       applicationId "XXXXXX"  
       minSdkVersion 11 
       targetSdkVersion 23  
       versionCode 29  
       versionName "2.66"  
       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' 
}

(3)在 AndroidManifest.xml 中的 application 标签中添加

1<?xml version="1.0" encoding="utf-8"?>2
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.example.android.multidex.myapplication">
      <application
      ...
       android:name="android.support.multidex.MultiDexApplication">
        ...
     </application>
 </manifest>

如果你的应用程序继承 Application , 那么你需要重写Application attachBaseContext方法

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

这样的话就可以和64K说拜拜了

转自:http://www.jianshu.com/p/f68b0b070c31

原文地址:https://www.cnblogs.com/YangBinChina/p/6656312.html