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.+ 手機上安裝了。