在使用AndroidStudio開發(fā)的時候,如果你的工程運行時出現(xiàn)了類似以下的錯誤输玷,則表示你工程所使用的方法數(shù)量已經(jīng)超過了65536個颈嚼。
Conversion to Dalvik format failed:
Unable to execute dex: method ID not in [0, 0xffff]: 65536
trouble writing output:
Too many field references: 131000; max is 65536.
You may try using --multi-dex option.
那為什么當(dāng)方法數(shù)超過這個數(shù)量時會有限制呢翔悠?
AndroidStudio官方文檔是這么說的:
Android application (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app. The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536—including Android framework methods, library methods, and methods in your own code. In the context of computer science, the term Kilo, K, denotes 1024 (or 2^10). Because 65,536 is equal to 64 X 1024, this limit is referred to as the '64K reference limit'.
<br />
Android應(yīng)用(APK)文件包含以Dalvik可執(zhí)行文件(DEX)的形式的可執(zhí)行字節(jié)碼文件,它包含編譯后的代碼用于運行您的應(yīng)用番宁。Dalvik可執(zhí)行的規(guī)范限制了方法總數(shù)可以在單個DEX文件內(nèi)引用到65536個,包括Android框架方法氮昧,引用庫的方法框杜,您自己代碼庫的方法浦楣。在計算機科學(xué)中,術(shù)語基洛咪辱,K振劳,表示1024(或2 ^ 10)。因為65536等于64 X 64,這個極限被稱為"64K引用限制"油狂。
<br />
那么怎么解決呢?只需三步操作:
1.修改你app(你所要解決的工程)的build.gradle文件:
android {
compileSdkVersion 21
buildToolsVersion "21.1.0"
defaultConfig {
...
minSdkVersion 14
targetSdkVersion 21
...
// Enabling multidex support.
multiDexEnabled true
}
...
}
這行multiDexEnabled true
是你需要添加的
2.給你的工程添加以下依賴历恐,依賴不一定要在app里的build.gradle,可以在app依賴的module或任意庫里添加:
dependencies {
compile 'com.android.support:multidex:1.0.1'
}
所使用的版本號現(xiàn)在最新為1.0.1
专筷,如果有提示更新的版本可用弱贼,改到最新版本即可。
3.在你自定義的Application類里重載以下方法:
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
//Avoiding the 64K Limit
MultiDex.install(this);
}
當(dāng)然磷蛹,如果沒有自定義的Application吮旅,你也可以在你的AndroidMainfest.xml里增加以下申明
<application
...
android:name="android.support.multidex.MultiDexApplication">
...
</application>
或者讓你自定義的Application繼承MultiDexApplication(不推薦)。
參考文檔:
https://developer.android.com/studio/build/multidex.html#avoid (需翻墻)