У меня довольно большой мультимодульный мультидексный проект, но недавно я получил ошибку при попытке выполнить сборку из командной строки (сборка {flavour Release)

Сообщение:

DexOverflowException: Cannot fit requested classes in the main-dex file

Вот еще логи из --debug build:

/Users/bartek/Documents/workspace/android/argus-android/Argus/app/build/intermediates/transforms/dexBuilder/argus/release/1114.jar
15:54:42.645 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.builder.dexing.D8DexArchiveMerger.getExceptionToRethrow(D8DexArchiveMerger.java:125)
15:54:42.645 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.builder.dexing.D8DexArchiveMerger.mergeDexArchives(D8DexArchiveMerger.java:110)
15:54:42.645 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.build.gradle.internal.transforms.DexMergerTransformCallable.call(DexMergerTransformCallable.java:101)
15:54:42.645 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.build.gradle.internal.transforms.DexMergerTransformCallable.call(DexMergerTransformCallable.java:36)
15:54:42.645 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   ... 47 more
15:54:42.645 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete
15:54:42.645 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.tools.r8.utils.ExceptionUtils.withCompilationHandler(ExceptionUtils.java:76)
15:54:42.645 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.tools.r8.utils.ExceptionUtils.withD8CompilationHandler(ExceptionUtils.java:45)
15:54:42.645 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.tools.r8.D8.run(D8.java:67)
15:54:42.645 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.builder.dexing.D8DexArchiveMerger.mergeDexArchives(D8DexArchiveMerger.java:108)
15:54:42.646 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   ... 49 more
15:54:42.646 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] Caused by: com.android.tools.r8.utils.AbortException
15:54:42.646 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.tools.r8.utils.Reporter.failIfPendingErrors(Reporter.java:77)
15:54:42.646 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.tools.r8.utils.Reporter.fatalError(Reporter.java:67)
15:54:42.646 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.tools.r8.utils.ExceptionUtils.withCompilationHandler(ExceptionUtils.java:62)
15:54:42.646 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   ... 52 more
15:54:42.646 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   Suppressed: com.android.tools.r8.errors.DexOverflowException: Cannot fit requested classes in the main-dex file (# methods: 65548 > 65536)
15:54:42.646 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.tools.r8.dex.VirtualFile.throwIfFull(VirtualFile.java:182)
15:54:42.646 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.tools.r8.dex.VirtualFile$DistributorBase.fillForMainDexList(VirtualFile.java:305)
15:54:42.646 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.tools.r8.dex.VirtualFile$FillFilesDistributor.run(VirtualFile.java:353)
15:54:42.646 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.tools.r8.dex.ApplicationWriter.distribute(ApplicationWriter.java:167)
15:54:42.646 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.tools.r8.dex.ApplicationWriter.write(ApplicationWriter.java:187)
15:54:42.646 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.tools.r8.D8.run(D8.java:167)
15:54:42.647 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.tools.r8.D8.lambda$run$0(D8.java:71)
15:54:42.647 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.tools.r8.utils.ExceptionUtils.withCompilationHandler(ExceptionUtils.java:58)
15:54:42.647 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.tools.r8.utils.ExceptionUtils.withD8CompilationHandler(ExceptionUtils.java:45)
15:54:42.647 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.tools.r8.D8.run(D8.java:67)
15:54:42.647 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.builder.dexing.D8DexArchiveMerger.mergeDexArchives(D8DexArchiveMerger.java:108)
15:54:42.647 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.build.gradle.internal.transforms.DexMergerTransformCallable.call(DexMergerTransformCallable.java:101)
15:54:42.647 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.build.gradle.internal.transforms.DexMergerTransformCallable.call(DexMergerTransformCallable.java:36)
15:54:42.647 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
15:54:42.647 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
15:54:42.647 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at java.util.concurrent.ForkJoinTask.externalAwaitDone(ForkJoinTask.java:326)
15:54:42.647 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at java.util.concurrent.ForkJoinTask.doJoin(ForkJoinTask.java:391)
15:54:42.647 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at java.util.concurrent.ForkJoinTask.join(ForkJoinTask.java:719)
15:54:42.648 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.google.common.collect.ImmutableList.forEach(ImmutableList.java:397)
15:54:42.648 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.build.gradle.internal.transforms.DexMergerTransform.transform(DexMergerTransform.java:221)
15:54:42.648 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:221)
15:54:42.648 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:217)
15:54:42.648 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
15:54:42.648 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:212)
15:54:42.648 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
15:54:42.648 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
15:54:42.648 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
15:54:42.648 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at java.lang.reflect.Method.invoke(Method.java:497)
15:54:42.648 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
15:54:42.648 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:50)
15:54:42.648 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
15:54:42.648 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
15:54:42.649 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:124)
15:54:42.649 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
15:54:42.649 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
15:54:42.649 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
15:54:42.649 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
15:54:42.649 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:113)
15:54:42.649 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:95)
15:54:42.649 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:73)
15:54:42.649 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
15:54:42.649 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:59)
15:54:42.649 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
15:54:42.649 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:59)
15:54:42.649 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:101)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.FinalizeInputFilePropertiesTaskExecuter.execute(FinalizeInputFilePropertiesTaskExecuter.java:44)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:88)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:62)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
15:54:42.650 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
15:54:42.651 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
15:54:42.651 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:623)
15:54:42.651 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:578)
15:54:42.651 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
15:54:42.651 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
15:54:42.651 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
15:54:42.651 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
15:54:42.651 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
15:54:42.651 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
15:54:42.651 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]       at java.lang.Thread.run(Thread.java:745)

Как я могу контролировать, что идет в основной файл dex? Как заставить основной файл dex содержать меньше методов?

Моя установка:

compileSdkVersion 27
buildToolsVersion '27.0.3'

Gradlew :

distributionUrl=https\://services.gradle.org/distributions/gradle-4.5-all.zip
plugin: classpath 'com.android.tools.build:gradle:3.2.0-alpha04'
2
Bartosz Kraszewski 21 Авг 2018 в 17:23

4 ответа

Лучший ответ

Я попробовал Александр Братусенко ответить, не помогло, но это хорошая подсказка. Что на самом деле помогло - я понизил плагин Gradle до

classpath 'com.android.tools.build:gradle:3.1.4'
1
Bartosz Kraszewski 22 Авг 2018 в 10:51

Для сборки релиза вы должны попытаться исправить это с помощью proguard. Для отладки вы можете попытаться исправить это, исключив некоторые классы из основного файла dex.

Добавьте это в модуль приложения

   import your.awesome.app.MainDexGenerator

   tasks.whenTaskAdded {
            if (it.name.contains('transformDexArchiveWithDexMergerFor') && it.name.contains('Debug')) {
                it.doFirst(new MainDexGenerator([
                        'io/reactivex/annotations',
                        'kotlin',
                        'com/fasterxml'
                        //....and other you think could work 
                ]))
            }
        }

Вы можете найти классы, которые Gradle хочет добавить к основному dex: intermeditates/legacy_multidex_main_dex_list/. Например, вы можете исключить неиспользуемые модели или что-то еще, в основном все, что вам не нужно при запуске класса Application. Не забудьте проверить, что вы ничего не сломали на API 19 или ниже

Установите buildSrc с build.gradle с отличным плагином.

В buildSrc / main / groovy / your / awesome / app добавьте свое действие:

@CompileStatic
class MainDexGenerator implements Action<Task> {

    private static final String MAIN_DEX_FILE = 'mainDexList.txt'

    // list we want to exclude frome MainDex
    private List<String> excludedList
    MainDexGenerator(List<String> excludedPackages) {
        excludedList = excludedPackages;
    }

    @Override
    void execute(Task task) {
        for (File inputFile : task.inputs.files.files) {
            if (inputFile.absolutePath.endsWith(MAIN_DEX_FILE)) {
                List<String> result = Files.lines(inputFile.toPath())
                        .filter { isNotMatch(it) }
                        .collect(Collectors.toList())
                Files.write(inputFile.toPath(), result, WRITE, TRUNCATE_EXISTING)
                break
            }
        }
    }

    private boolean isNotMatch(String line) {
        for (String item : excludedList) {
            if (line.contains(item)) {
                return false
            }
        }
        return true
    }
}

Чтобы увидеть итоговое количество методов, вы можете использовать инструмент apkAnalyzer. Ищите первый Декс.

Также вы можете попытаться реорганизовать ваш код и извлечь некоторые обязанности из класса приложения.

Вы также можете попытаться увеличить minApi до 21.

В этом ответе есть еще несколько подробностей о проблеме много классов в --main-dex-list, превышена емкость основного dex

1
Maksim Turaev 4 Сен 2019 в 08:12

Здесь на самом деле вы пересекаете количество методов dex 65536 (, что означает, что вы можете использовать только 65536 методов в вашем apk ), и вы всего на 12 методов впереди 😎

DexOverflowException: Невозможно разместить запрошенные классы в файле main-dex (# методы: 65548> 65536)

Лучшее предложение, вы должны действительно уменьшить нет. количество методов.

  • Удалить неиспользуемую библиотеку
  • Если вы используете только часть библиотеки, попробуйте определить свой собственный метод и реализовать его.

Эта ссылка будет полезна соблюдать ваш счет метода dex.

Но если вам действительно нужно использовать метод dex count более 65536, вы должны проверить это включить. multidex

удачного кодирования!

-3
deepak kumar 22 Авг 2018 в 11:38

Отключение хранения аннотированных классов во время выполнения может помочь. Просто поместите его в раздел android {} каждого файла модуля gradle.

dexOptions {
        preDexLibraries = false
        keepRuntimeAnnotatedClasses false
    }

Обычно это происходит, когда в проекте интенсивно используется кинжал 2

0
Alexander Bratusenko 21 Авг 2018 в 17:06
51950860