1. 程式人生 > >安卓應用方法數超過64k解決辦法:分割Dex

安卓應用方法數超過64k解決辦法:分割Dex

con 文件 jar extends iter 介紹 安卓 只需要 option

你的安卓項目功能很強大,對接了好多第三方開源庫,項目越做越完善,代碼越敲越爽。可是突然有一天報異常了。
錯誤:The number of method references in a .dex file cannot exceed 64K.
編譯器提醒你,你的項目方法數超過64k了。

AndroidStudio會提醒你:
Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html

如果你覺得看英文文檔累,那就跟小編一起,使用Google官網提供的分包策略(即:分割Dex)解決方法數超64k限制問題吧。
但是對於eclipse編譯器來說,怎麽辦呢?看來你要使用Google官網解決方案只能先想辦法將項目搬家到AndroidStudio上了。
【也許網上有更好的解決方案,比如使用插件化框架:https://github.com/singwhatiwanna/dynamic-load-apk】

我還是覺得Google官網的解決方案比較靠譜,那麽開始吧。

第一步:引入Google提供的multidex庫(com.android.support:multidex:1.0.1)

技術分享

第二步:開啟multiDexEnabled(即:在defaultConfig中添加屬性:multiDexEnabled true)

技術分享

第三步:將項目原Application更改為MultiDexApplication

此時有兩種情況:

1> 如果你的項目沒有重寫Application類,那麽你只需要更改AndroidManifest.xml文件的application標簽,即在application標簽下添加屬性:android:name=”android.support.multidex.MultiDexApplication”即可。
技術分享

2> 如果你的項目重寫了Application類,那麽你需要將你的Application類去除繼承android.app.Application,改為繼承android.support.multidex.MultiDexApplication類,然後重寫attachBaseContext(Context base);方法,並對MultiDex進行初始化即可。如下:

public class MyApplication extends MultiDexApplication {
    @Override
        protected void attachBaseContext(Context base) {
            super.attachBaseContext(base);
            MultiDex.install(this); // 初始化
        }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

這時候分包就完成了。

另外請註意:Out of memory 問題

1> 對於有很多依賴的項目,編譯可能因為下面的錯誤中斷

Error:Execution failed for task ‘:app:dexDebug‘. 
Error Code:3
Output: 
      UNEXPECTED TOP-LEVEL ERROR: 
      java.lang.OutOfMemoryError: GC overhead limit exceeded at...
  • 1
  • 2
  • 3
  • 4
  • 5

解決辦法:
編輯app下build.gralde文件,在android下添加如下屬性即可:

dexOptions {
    incremental true
    javaMaxHeapSize ‘2g‘
}
  • 1
  • 2
  • 3
  • 4

2> 如果你的項目有一些依賴庫(Module)項目,希望你在其build.gralde文件的defaultConfig中也添加屬性:multiDexEnabled true
技術分享

至此,分包策略就介紹完了。基本上可以解決掉方法數超過64k限制問題。但是也會有一些副作用,比如導致項目啟動非常緩慢甚至ANR。

安卓應用方法數超過64k解決辦法:分割Dex