√ 點下「Build」→「Build APK」後出現錯誤,雖專案可編譯但APK無法建置成功。
錯誤碼:Error:Execution failed for task ':TeachAIO:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
原因為單個Dex的方法數量過多,超過64K(65536),其中一種解決方法為:開啟multiDexEnabled,參考Android官網:Enable Multidex for Apps with Over 64K Methods
以下為開啟multiDexEnabled之步驟:
1️⃣ 修改「build.gradle (Module:app)」中的「android」→「defaultConfig」,設定multiDexEnabled參數。
android { defaultConfig { ... minSdkVersion 18 targetSdkVersion 26 multiDexEnabled true //<--Add This } ... }
2️⃣ 修改「build.gradle (Module:app)」中的「dependencies」,增添編譯multiDex庫。
dependencies { ... compile 'com.android.support:multidex:1.0.1' //<--Add This ... }
3️⃣ 依照專案狀態執行以下其中一種操作。
⌾ 未覆蓋Application類別(未撰寫自己的Application Class):修改「AndroidManifest.xml」,在「<application>」標記中設置「android:name」。
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.myapp"> <application ... android:name="android.support.multidex.MultiDexApplication" > ... </application> </manifest>
⌾ 已重寫Application類別:修改「Application.java」,將Application類別更改為繼承「MultiDexApplication」。
import android.support.multidex.MultiDexApplication; //import This. //public class Application extends android.app.Application { //Here is original code. public class Application extends MultiDexApplication { ... } //Modify This.
⌾ 已重寫Application類別,但無法更改基本類別:於「Application.java」中覆蓋「attachBaseContext()」方法,並呼叫「MultiDex.install(this);」以啟用multidex。
public class MyApplication extends SomeOtherApplication { @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } }
註:最後使用第二種「已重寫Application類別」之方法,故其他方法未實作過。
註:上述之解決方法會拉長APK之建置時間,參考許多資料後發現出現此錯誤主要是加入Google Play Service,因而載入過多沒有使用到的Library。
其他解決方法為依照所需功能加入Google Service API,而非直接載入整個Google Service,但因此方法於目前的狀態不適用,故無法實作。
√ 再次點下「Build」→「Build APK」後出現錯誤,一樣無法建置APK。
錯誤碼:Error:Execution failed for task ':TeachAIO:transformClassesWithJarMergingForDebug'.
> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: android/support/v4/animation/AnimatorCompatHelper.class
最後推測是版本不相容,於「build.gradle (Module:app)」中加入以下程式碼後便可解決。
configurations.all { resolutionStrategy.eachDependency { DependencyResolveDetails details -> def requested = details.requested if (requested.group == 'com.android.support') { if (!requested.name.startsWith("multidex")) { details.useVersion '25.4.0' } } } }
再執行一次「Build」→「Build APK」,即得到「APK(s) generated successfully.」。
參考資料:
https://developer.android.com/studio/build/multidex.html
https://github.com/h6ah4i/android-advancedrecyclerview/issues/396