Android 系统中,一个 dex 文件中存储方法 id 用的是 short 类型数据,这就规定了 dex 文件中方法不能超过 65K,编译打包过程当应用的方法数达到 65536 后,编译器就无法完成编译工作,并抛出异常:
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
at com.android.dx.merge.DexMerger$6.updateIndex(DexMerger.java:502)
at com.android.dx.merge.DexMerger$IdMerger.mergeSorted(DexMerger.java:283)
at com.android.dx.merge.DexMerger.mergeMethodIds(DexMerger.java:491)
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:168)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:502)
at com.android.dx.command.dexer.Main.runMonoDex(Main.java:334)
at com.android.dx.command.dexer.Main.run(Main.java:277)
at com.android.dx.command.dexer.Main.main(Main.java:245)
at com.android.dx.command.Main.main(Main.java:106)
Android studio 中,解决方法:
1. 确定使用 Android SDK Build Tools 21.1 及以上版本,修改 build.gradle 文件,添加配置
android {
compileSdkVersion 24
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "com.xxx.xxx"
minSdkVersion 15
targetSdkVersion 22
versionCode 150
versionName "1.5.0"
multiDexEnabled true
}
...
}
2. 在 dependencies 中添加 multidex 的依赖
compile 'com.android.support:multidex:1.0.1'
3. 在代码中介入支持 multidex 的功能代码
有三种可行的办法:
(1) 在 manifest 文件中指定 application 为 MultiDexApplication
<application
android:name="android.support.multidex.MultiDexApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
...
</application>
(2) 自定义的 Application 类继承 MultiDexApplication
public class YourApplication extends MultiDexApplication{
...
}
(3) 不想改变自定义的 Application 类,可在 Application 类中重写 attachBaseContext 方法
public class YourApplication extends Application{
...
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this );
}
...
}
通过上面步骤稳稳地解决方法数越界问题,你还会发现一点,通过编译的应用可以在 Android 2.+ 手机上安装了。