Ошибка "Cannot fit requested classes in a single dex file" в Andoid studio

При запуске проекта в Andoid studio (зелёный треугольник) получаю 4 ошибки

Cannot fit requested classes in a single dex file (# methods: 67080 > 65536)
Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete
Caused by: com.android.tools.r8.utils.b: Error: null, Cannot fit requested classes in a single dex file (# methods: 67080 > 65536)
Error: null, Cannot fit requested classes in a single dex file (# methods: 67080 > 65536)

Удалось нагулить, что это связано с чем-то из build.gradle, дальше неосилил.

Помогите разобраться с чем проблема. (Сорри если что не так - я нуб, только начинаю путь в разработке моб приложений)

Код build.gradle (Project:MyApp):

buildscript {
    repositories {
        jcenter()
        google()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        maven { url 'https://plugins.gradle.org/m2/'}
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.1'
        classpath 'com.google.gms:google-services:4.3.4'
        classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:0.12.6'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()  // Google's Maven repository
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


Код build.gradle (Module:App):

apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"

    defaultConfig {
        applicationId "com.super.app"
        minSdkVersion 16
        targetSdkVersion 29
        versionCode 4
        versionName "1.3"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    android {
        defaultConfig {
            manifestPlaceholders = [
                    onesignal_app_id: 'xxx-xxx-xxx-xxx-xxx',// Тут реальный app_id
            ]
        }
    }
}


dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.google.android.gms:play-services-ads:19.0.1'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation 'com.google.firebase:firebase-analytics:17.2.3'
    implementation 'com.onesignal:OneSignal:3.12.6'
    implementation platform('com.google.firebase:firebase-bom:26.1.1')
}

Ответы (1 шт):

Автор решения: Анастасия

Вы получаете эту ошибку, потому что вы достигли и перешли предел архитектуры сборки Android - один файл DEX может содержать только около 64 тысяч ссылок.

Чтобы решить эту проблему, есть несколько вариантов.

  • Используйте multi-dex. Вместо одного DEX-файла в вашем APK будет несколько dex-файлов. Вы можете следовать этому руководству, чтобы установить его в файлы сборки. Это может повлиять на вашу минимальную версию SDK.

Попробуйте в файле build.gradle (app) добавить в зависимости следующее:

implementation 'com.android.support:multidex:1.0.3'

И в defaultConfig:

multiDexEnabled true
  • Используйте Proguard или R8 - помимо прочего, эти инструменты обеспечивают сжатие кода. Это означает, что весь неиспользуемый код будет удален, и поэтому предел в 64 КБ не должен быть достигнут. Вы можете следовать этому руководству, чтобы настроить сжатие кода.

Надеюсь, что-то из этого поможет. Больше вариантов можно найти в англоязычном stackoverflow.

→ Ссылка