1. 程式人生 > >Andorid 方法數超過64K的問題

Andorid 方法數超過64K的問題

其實早就聽過64K這個問題,只是覺得目前所做的專案較小,應該不會有這個問題。出現這個問題的直接原因我覺得應該是整合進了高德地圖的三個jar包:309KB、377KB、474KB。然後的某天突然就提示64K的問題了,最開始我把無用的jar包刪除了兩個,沒過三天,又出現了,以下是Android studio的提示:

Error:The number of method references in a .dex file cannot exceed 64K.
Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html

不僅給出了錯誤原因,還給出瞭解決方案:https://developer.android.com/tools/building/multidex.html
這個文件說明了出現這個錯誤的原因、解決辦法及優化方案,值得一看。
解決方案也很簡單,兩步:
* 在build.gradle裡面加入multiDexEnabled true

    defaultConfig {
        ...
        minSdkVersion 14
        targetSdkVersion 21
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
  • 在Application裡面重寫 attachBaseContext 方法
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

問題解決。