由于 .dex 文件错误,我无法构建我的应用程序。 (Android)

I can't build my app because of .dex file error. (Android)

如果我想在 Android Studio 中构建 APK,我这里有一个小问题 我收到此错误消息:

Error:The number of method references in a .dex file cannot exceed 64K.

https://developer.android.com/tools/building/multidex.html

了解如何解决此问题
Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
 com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException:
 java.util.concurrent.ExecutionException: 
 com.android.ide.common.process.ProcessException:
 org.gradle.process.internal.ExecException:
     Process 'command '/usr/local/java/jdk1.8.0_77/bin/java'' finished with non-zero exit value 2

我在 Whosebug 上找到了一个答案,说要在我的 Gradle 文件中编译这个依赖项:

compile 'com.android.support:multidex:1.0.0'

但这没有用。

这是我的 Gradle 文件:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'com.google.android.gms:play-services:9.0.2'
    compile 'com.android.support:multidex:1.0.0'
}

在你的 android { // } build.gradle 文件中试试这个:

dexOptions {
    javaMaxHeapSize "4g"
    incremental true
    preDexLibraries = false
}

然后在你的依赖中,添加这个:

dependencies{
   compile 'com.android.support:multidex:1.0.1'
}

更新

如果您在项目中扩展应用程序,请切换为扩展此应用程序:

public class MyApp extends MultiDexApplication{

   //inside here, override

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

最后,在AndroidManifest文件中设置你的应用名称为

<application 
   android:name=".MyApp">

这应该可以让您避免这个问题;祝你好运!

您需要在应用程序中启用多索引,方法是将 build.gradle 中的 multiDexEnabled 标志设置为 true。请记住,您的最低 SDK 版本也必须为 14 或更高版本。

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.0"

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

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.0'
}

然后,在清单中配置您的应用程序元素:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>