app:transformClassesWithDexDebug错误

今天导入一个第三方库的时候,Android Studio构建失败了。

Message 报错:

   Error:Execution failed for task ':app:transformClassesWithDexForBaiduDebug'.
com.android.build.api.transform.TransformException:   
com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: 
Process 'command '/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home/bin/java'' finished with non-zero exit value 3

Gradle 报错:

   UNEXPECTED TOP-LEVEL EXCEPTION: java.lang.IllegalArgumentException: method ID not in [0, 0xffff]: 65536 
at com.android.dx.merge.DexMerger$6.updateIndex(DexMerger.java:501) 
at com.android.dx.merge.DexMerger$IdMerger.mergeSorted(DexMerger.java:276) 
at com.android.dx.merge.DexMerger.mergeMethodIds(DexMerger.java:490) 
at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:167) 
at com.android.dx.merge.DexMerger.merge(DexMerger.java:188) 
at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439) 
at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287) 
at com.android.dx.command.dexer.Main.run(Main.java:230) 
at com.android.dx.command.dexer.Main.main(Main.java:199) 
at com.android.dx.command.Main.main(Main.java:103):Derp:dexDerpDebug FAILED

分析错误:

Dex文件保存所有Classes的方法个数的范围在0~65535之间,引用的第三方库比较多,已经超过了这个范围了。

那怎么办呢?Goolge 给出补丁方案:

第1步、修改gradle脚本来产生多个dex。

android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    ...
    minSdkVersion 16
    targetSdkVersion 23
    ...

    // Enabling multidex support.
    multiDexEnabled true
}
...
}
dependencies {
    compile 'com.android.support:multidex:1.0.0'
}

第2步、重写Application的attachBaseContext()这个方法。

@Override
protected void attachBaseContext(Context context) {
    super.attachBaseContext(context);
    MultiDex.install(this);     
}

重新run一下。Gradle还报错:

java.lang.OutOfMemoryError: GC overhead limit exceeded

在gradle android里添加:

dexOptions {    
       javaMaxHeapSize "2g"
}

来增加java堆内存大小。

完整的gradle:

android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    ...
    minSdkVersion 16
    targetSdkVersion 23
    ...

    // Enabling multidex support.
    multiDexEnabled true
}

dexOptions {    
       javaMaxHeapSize "2g"
}
...
}
dependencies {
    compile 'com.android.support:multidex:1.0.0'
}

重新run可以了。

你可能感兴趣的:(app:transformClassesWithDexDebug错误)