Android Gradle plugin 9.0 — это крупный релиз, вносящий изменения в API и поведение программы.
Для обновления до плагина Android Gradle версии 9.0.1 используйте помощник обновления плагина Android Gradle . Помощник обновления AGP помогает сохранить существующее поведение при обновлении проекта, когда это необходимо, поэтому вы можете обновить свой проект до AGP 9.0, даже если вы не готовы принять все новые настройки по умолчанию в AGP 9.0.
Также доступны два навыка агента, которые упростят процесс обновления. Для приложений, не использующих KMP, попробуйте навык обновления AGP 9 из репозитория навыков Android. Для приложений, использующих KMP, попробуйте навык обновления AGP 9 от JetBrains. Дополнительную информацию об использовании навыков в Android Studio см. в разделе «Расширение режима агента с помощью навыков» .
Совместимость
Максимальный уровень API, поддерживаемый плагином Android Gradle 9.0, — 36.1. Вот дополнительная информация о совместимости:
| Минимальная версия | Версия по умолчанию | Примечания | |
|---|---|---|---|
| Грэдл | 9.1.0 | 9.1.0 | Для получения более подробной информации см. раздел «Обновление Gradle» . |
| Инструменты сборки SDK | 36.0.0 | 36.0.0 | Установите или настройте инструменты сборки SDK. |
| НДК | Н/Д | 28.2.13676358 | Установите или настройте другую версию NDK. |
| JDK | 17 | 17 | Для получения более подробной информации см. раздел «Настройка версии JDK» . |
В классах android DSL теперь реализованы только новые публичные интерфейсы.
За последние несколько лет мы внедрили новые интерфейсы для нашего DSL и API, чтобы лучше контролировать, какие API являются публичными. В версиях AGP 7.x и 8.x по-прежнему использовались старые типы DSL (например, BaseExtension ), которые также реализовывали новые публичные интерфейсы, чтобы сохранить совместимость по мере развития работы над интерфейсами.
AGP 9.0 использует исключительно наши новые DSL-интерфейсы, а в реализациях используются новые, полностью скрытые типы. Это также исключает доступ к старому, устаревшему API вариантов.
Для обновления до AGP 9.0 может потребоваться выполнить следующие действия:
- Убедитесь, что ваш проект совместим со встроенным Kotlin : плагин
org.jetbrains.kotlin.androidнесовместим с новым DSL. Переключитесь на плагин библиотеки Android Gradle для KMP в проектах KMP: использование плагина
org.jetbrains.kotlin.multiplatformв том же подпроекте Gradle, что и плагиныcom.android.libraryиcom.android.application, несовместимо с новым DSL.Обновите файлы сборки: хотя изменение интерфейсов призвано сохранить DSL максимально похожим, могут быть некоторые небольшие изменения .
Update your custom build logic to reference the new DSL and API: Replace any references to the internal DSL with the public DSL interfaces. In most cases this will be a one-to-one replacement. Replace any use of the
applicationVariantsand similar APIs with the newandroidComponentsAPI . This might be more complex, as theandroidComponentsAPI is designed to be more stable to keep plugins compatible longer. Check our Gradle Recipes for examples.Обновите сторонние плагины: некоторые сторонние плагины могут по-прежнему зависеть от интерфейсов или API, которые больше не доступны. Перейдите на версии этих плагинов, совместимые с AGP 9.0.
Переход на новые DSL-интерфейсы предотвращает использование плагинами и скриптами сборки Gradle различных устаревших API, в том числе:
Устаревший API в блоке android | Функция | Замена |
|---|---|---|
applicationVariants ,libraryVariants ,testVariants иunitTestVariants | Точки расширения для плагинов, добавляющих новые функции в AGP. | Замените это, например, на API androidComponents.onVariants :androidComponents { onVariants() { variant -> variant.signingConfig .enableV1Signing.set(false) } } |
variantFilter | Позволяет отключить выбранные варианты. | Замените это, например, на API androidComponents.beforeVariants : androidComponents { beforeVariants( selector() .withBuildType("debug") .withFlavor("color", "blue") ) { variantBuilder -> variantBuilder.enable = false } } |
deviceProvider иtestServer | Регистрация пользовательских тестовых сред для запуска тестов на устройствах и эмуляторах Android. | Переключитесь на устройства, управляемые Gradle . |
sdkDirectory ,ndkDirectory ,bootClasspath ,adbExecutable иadbExe | Использование различных компонентов Android SDK для выполнения пользовательских задач. | Переключитесь на androidComponents.sdkComponents . |
registerArtifactType ,registerBuildTypeSourceProvider ,registerProductFlavorSourceProvider ,registerJavaArtifact ,registerMultiFlavorSourceProvider иwrapJavaSourceSet | Устаревшая функциональность, в основном связанная с обработкой сгенерированных исходных файлов в Android Studio, перестала работать в AGP 7.2.0. | Прямых аналогов этим API не существует. |
dexOptions | Устаревшие настройки, связанные с инструментом dx , который был заменен на d8 . Ни одна из настроек не оказывает никакого эффекта начиная с плагина Android Gradle версии 7.0. | Прямой замены нет. |
generatePureSplits | Создавайте разделы конфигурации для мгновенных приложений. | Возможность разделять конфигурацию на отдельные компоненты теперь встроена в пакеты приложений Android. |
aidlPackagedList | Файлы AIDL для включения в AAR-архив, чтобы предоставить к нему доступ в качестве API для библиотек и приложений, зависящих от этой библиотеки. | Эта функция по-прежнему доступна для расширений типа LibraryExtension , но не для других типов расширений. |
Если после обновления до AGP 9.0 вы видите следующее сообщение об ошибке, это означает, что ваш проект по-прежнему ссылается на некоторые старые типы:
java.lang.ClassCastException: class com.android.build.gradle.internal.dsl.ApplicationExtensionImpl$AgpDecorated_Decorated
cannot be cast to class com.android.build.gradle.BaseExtension
Если вас блокируют несовместимые сторонние плагины, вы можете отказаться от них и вернуть старые реализации DSL, а также старый вариант API. При этом новые интерфейсы также будут доступны, и вы сможете обновить свою логику сборки в соответствии с новым API. Чтобы отказаться от них, добавьте следующую строку в файл gradle.properties :
android.newDsl=false
В качестве альтернативы, для более постепенной миграции, AGP 9.4 позволяет отказаться от отдельных модулей. Чтобы узнать, как это сделать, см. раздел «Отказ от модулей Variant API» .
В AGP 9.0 предыдущие классы помечены как устаревшие. Это означает, что проекты, которые откажутся от флага newDsl будут видеть предупреждения об устаревании, в том числе и в самом блоке android .
Вы также можете начать обновление до новых API до обновления до AGP 9.0. Новые интерфейсы присутствовали во многих версиях AGP, поэтому у вас может быть сочетание новых и старых. В справочной документации по API AGP показан интерфейс API для каждой версии AGP, а также дата добавления каждого класса, метода и поля.
Мы обращаемся к авторам часто используемых плагинов, чтобы помочь им адаптировать и выпустить плагины, полностью совместимые с новыми режимами, и продолжим совершенствовать AGP Upgrade Assistant в Android Studio, чтобы помочь вам в процессе миграции.
Если вы обнаружите, что в новом DSL или API вариантов отсутствуют необходимые возможности или функции, пожалуйста, как можно скорее сообщите об этом, создав соответствующую проблему .
Встроенный Kotlin
В плагине Android Gradle версии 9.0 реализована встроенная поддержка Kotlin, которая включена по умолчанию. Это означает, что вам больше не нужно применять плагин org.jetbrains.kotlin.android (или kotlin-android ) в файлах сборки для компиляции исходных файлов Kotlin. Это упрощает интеграцию Kotlin с AGP, позволяет избежать использования устаревших API и в некоторых случаях повышает производительность.
Поэтому при обновлении проекта до AGP 9.0 вам также необходимо перейти на встроенный Kotlin или отказаться от него .
Вы также можете выборочно отключать встроенную поддержку Kotlin для подпроектов Gradle, которые не содержат исходный код на Kotlin.
Зависимость от плагина Kotlin Gradle во время выполнения
To provide built-in Kotlin support, Android Gradle plugin 9.0 now has a runtime dependency on Kotlin Gradle plugin (KGP) 2.2.10. That means you no longer have to declare a KGP version, and if you use a KGP version lower than 2.2.10, Gradle will automatically upgrade your KGP version to 2.2.10. Likewise, if you use a KSP version lower than 2.2.10-2.0.2, AGP will upgrade it to 2.2.10-2.0.2 to match the KGP version.
Обновите KGP до более новой версии.
Для использования более новой версии KGP или KSP добавьте следующее в главный файл сборки:
buildscript {
dependencies {
// For KGP
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:KGP_VERSION")
// For KSP
classpath("com.google.devtools.ksp:symbol-processing-gradle-plugin:KSP_VERSION")
}
}
Понизьте версию KGP до более старой.
Понижение версии KGP возможно только в том случае, если вы отказались от встроенного Kotlin . Это связано с тем, что AGP 9.0 по умолчанию включает встроенный Kotlin, а для его использования требуется KGP 2.2.10 или выше.
Чтобы использовать более старую версию KGP или KSP, укажите эту версию в файле сборки верхнего уровня, используя строгое указание версии :
buildscript {
dependencies {
// For KGP
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin") {
version { strictly("KGP_VERSION") }
}
// For KSP
classpath("com.google.devtools.ksp:symbol-processing-gradle-plugin") {
version { strictly("KSP_VERSION") }
}
}
}
Обратите внимание, что минимальная версия KGP, до которой можно откатиться, — 2.0.0.
Поддержка тестовых стендов в IDE
AGP 9.0 обеспечивает полную поддержку тестовых наборов в среде разработки Android Studio.
Плагин объединенной библиотеки
Плагин Fused Library (предварительная версия) позволяет публиковать несколько библиотек в виде единого Android Library AAR-файла. Это может упростить пользователям использование опубликованных вами артефактов.
Для получения информации о начале работы см. раздел «Публикация нескольких библиотек Android как одной с помощью Fused Library» .
Изменения в поведении
В плагине Android Gradle версии 9.0 появились следующие новые возможности:
| Поведение | Рекомендация |
|---|---|
В плагине Android Gradle версии 9.0 по умолчанию используется версия NDK r28c . | Рекомендуется явно указать версию NDK, которую вы хотите использовать. |
| В плагине Android Gradle версии 9.0 по умолчанию требуется, чтобы пользователи библиотеки использовали ту же или более новую версию SDK для компиляции. | Используйте тот же или более новый SDK компиляции при работе с библиотекой. Если это невозможно, или вы хотите дать пользователям опубликованной вами библиотеки больше времени на переключение, явно установите параметр AarMetadata.minCompileSdk . |
В AGP 9.0 внесены изменения в значения по умолчанию для следующих свойств Gradle. Это позволяет сохранить поведение AGP 8.13 при обновлении:
| Свойство | Функция | Переход с AGP 8.13 на AGP 9.0 | Рекомендация |
|---|---|---|---|
android. newDsl | Используйте новые DSL-интерфейсы, не раскрывая устаревшие реализации блока android .Это также означает, что устаревший API для работы с вариантами приложений, такой как android.applicationVariants , больше недоступен. | false → true | Вы можете отказаться от этого, установив параметр android.newDsl=false .После того, как все плагины и логика сборки, используемые вашим проектом, будут совместимы, удалите опцию отказа от участия. |
android. builtInKotlin | Включает встроенные функции Kotlin. | false → true | По возможности перейдите на встроенный Kotlin или откажитесь от него . |
android. uniquePackage Names | Обеспечивает наличие у каждой библиотеки уникального имени пакета. | false → true | Укажите уникальные имена пакетов для всех библиотек в вашем проекте. Если это невозможно, вы можете отключить этот флаг во время миграции. |
android. useAndroidx | По умолчанию используются зависимости androidx . | false → true | Используйте зависимости androidx . |
android. default. androidx. test. runner | По умолчанию тесты на устройстве запускаются с помощью класса androidx.test.runner.AndroidJUnitRunner , заменяя устаревший класс InstrumentationTestRunner по умолчанию. android {
defaultConfig {
testInstrumentationRunner = "..."
}
} | false → true | Используйте AndroidJUnitRunner или явно укажите свой собственный testInstrumentationRunner . |
android. dependency. useConstraints | Управляет использованием ограничений зависимостей между конфигурациями. В AGP 9.0 по умолчанию установлено значение false , что означает использование ограничений только в тестах приложений на устройствах (AndroidTest). Установка значения true вернет поведение версии 8.13. | true → false | Не используйте ограничения зависимостей везде, если в этом нет необходимости. Принятие нового значения по умолчанию для этого флага также включает оптимизацию процесса импорта проекта, что должно сократить время импорта для сборок с большим количеством подпроектов библиотек Android. |
android. enableApp CompileTime RClass | Компиляция кода в приложениях с использованием нефинального класса R приводит компиляцию приложения в соответствие с компиляцией библиотеки. Это повышает эффективность поэтапного внедрения и открывает путь для будущей оптимизации производительности процесса обработки ресурсов. | false → true | Во многих проектах можно просто перенять новое поведение без изменений в исходном коде. Если поля класса R используются где-либо, где требуется константа, например, в операторах switch, следует провести рефакторинг, используя цепочки операторов if. |
android. sdk. defaultTargetSdk ToCompileSdk IfUnset | В приложениях и тестах в качестве значения по умолчанию для целевой версии SDK используется версия скомпилированного SDK. До внесения этого изменения целевая версия SDK по умолчанию устанавливалась на минимальную версию SDK. | false → true | Для приложений и тестов явно укажите целевую версию SDK. |
android. onlyEnableUnitTest ForTheTested BuildType | Создаёт компоненты модульных тестов только для тестируемого типа сборки. В проекте по умолчанию это приводит к созданию одного модульного теста для отладки, тогда как ранее модульные тесты запускались либо для отладки, либо для выпуска. | false → true | Если в вашем проекте не требуется запуск тестов как в режиме отладки, так и в режиме выпуска, никаких изменений не требуется. |
android. proguard. failOnMissingFiles | Сборка завершается с ошибкой, если какой-либо из файлов, указанных в AGP DSL, отсутствует на диске. До этого изменения опечатки в именах файлов приводили к тому, что файлы игнорировались без предупреждения. | false → true | Удалите все недействительные объявления файлов ProGuard. |
android. r8. optimizedResourceShrinking | Позволяет R8 использовать меньше ресурсов Android, рассматривая классы и ресурсы Android совместно. | false → true | Если правила сохранения данных в вашем проекте уже настроены, никаких изменений не требуется. |
android. r8. strictFullMode ForKeepRules | Это позволяет R8 сохранять меньше элементов, не сохраняя неявно конструктор по умолчанию, когда класс сохраняется. То есть, -keep class A больше не подразумевает -keep class A { <init>(); } | false → true | Если правила сохранения данных в вашем проекте уже настроены, никаких изменений не требуется. Замените -keep class A на -keep class A { <init>(); } в правилах сохранения в вашем проекте для тех случаев, когда необходимо сохранить конструктор по умолчанию. |
android. defaults. buildfeatures. resvalues | Включает resValues во всех подпроектах | true → false | Включите resValues только в тех подпроектах, которым это необходимо, установив следующие параметры в файлах сборки Gradle этих проектов: android {
buildFeatures {
resValues = true
}
} |
android. defaults. buildfeatures. shaders | Включает компиляцию шейдеров во всех подпроектах. | true → false | Разрешите компиляцию шейдеров только в тех подпроектах, которые содержат шейдеры, подлежащие компиляции, установив следующие параметры в файлах сборки Gradle этих проектов: android {
buildFeatures {
shaders = true
}
} |
android. r8. proguardAndroidTxt. disallowed | В AGP 9.0 getDefaultProguardFile() будет поддерживать только proguard-android-optimize.txt а не proguard-android.txt . Это сделано для предотвращения случайного использования флага dontoptimize , который включен в proguard-android.txt . | false → true | Чтобы избежать оптимизации, вы можете явно указать dontoptimize в пользовательском файле proguardFile, а также использовать файл proguard-android-optimize.txt . По возможности удалите флаг dontoptimize из этого файла, так как он снижает преимущества оптимизации R8. В противном случае откажитесь от оптимизации, установив параметр android.r8.globalOptionsInConsumerRules.disallowed=false . |
android. r8. globalOptions InConsumerRules. disallowed | From AGP 9.0, Android library and feature module publishing will fail if consumer keep files contain problematic Proguard configurations. Consumer keep files that include global options like dontoptimize or dontobfuscate should only be used in application modules, and can reduce optimization benefits for library users. Android App module compilation will silently ignore any such global options if embedded in a pre-compiled dependency (JAR or AAR). You can see when this occurs by checking configuration.txt (typically in a path like <app_module>/build/outputs/mapping/<build_variant>/configuration.txt ) for comments like: # REMOVED CONSUMER RULE: dontoptimize | false → true | Опубликованные библиотеки должны удалить все несовместимые правила. Внутренние библиотеки должны переместить все несовместимые, но необходимые правила в файл proguardFile в модуле приложения. Отключить эту опцию можно, установив параметр android.r8.globalOptionsInConsumerRules.disallowed=false . После того, как все ваши файлы keep потребителя будут совместимы, снимите опцию отключения. |
android. sourceset. disallowProvider | Запретить передачу поставщиков для сгенерированных исходных файлов с использованием DSL AndroidSourceSet . | false → true | Используйте API Sources в androidComponents для регистрации сгенерированных исходных файлов. |
android. custom. shader. path. required | Если компиляция шейдеров включена, необходимо явно указать путь к компилятору шейдеров в файле local.properties . | false → true | Добавьте glslc.dir=/path/to/shader-tools в local.properties вашего проекта. |
Удалённые функции
В плагине Android Gradle версии 9.0 удалена следующая функциональность:
- Поддержка приложений Embedded Wear OS
В AGP 9.0 прекращена поддержка встраивания приложений Wear OS, которая больше не поддерживается в Play Store. Это включает в себя удаление конфигурацийwearAppи DSLAndroidSourceSet.wearAppConfigurationName. Инструкции по публикации приложения в Wear OS см. в разделе «Распространение в Wear OS». - задача отчета
androidDependenciesиsourceSetsAndroid - Поддержка разделения по плотности APK
В AGP 9.0 удалена поддержка создания разделенных APK-файлов на основе плотности экрана. Функциональность и связанные с ней API были удалены. Для разделения APK-файлов на основе плотности экрана с использованием AGP 9.0 или более поздних версий используйте пакеты приложений .
Изменен DSL
В плагине Android Gradle версии 9.0 внесены следующие изменения в DSL, нарушающие совместимость:
Параметризация
CommonExtensionудалена.Само по себе это всего лишь изменение на уровне исходного кода, призванное предотвратить подобные изменения в будущем, но оно также означает, что методы блока необходимо перенести из
CommonExtensionвApplicationExtension,LibraryExtension,DynamicFeatureExtensionиTestExtension.При обновлении проекта до AGP 9.0 проведите рефакторинг кода плагина Gradle, использующего эти параметры или методы блоков. Например, следующий плагин обновлен таким образом, чтобы удалить параметр типа и не полагаться на удаленные методы блоков:
AGP 8.13
val commonExtension: CommonExtension<*, *, *, *, *, *> = extensions.getByType(CommonExtension::class) commonExtension.apply { defaultConfig { minSdk { version = release(28) } } }AGP 9.0
val commonExtension: CommonExtension = extensions.getByType(CommonExtension::class) commonExtension.apply { defaultConfig.apply { minSdk { version = release(28) } } }Для плагинов, ориентированных на широкий диапазон версий AGP, прямое использование геттера обеспечивает бинарную совместимость с версиями AGP ниже 9.0.
Удалён DSL
В плагине Android Gradle версии 9.0 удалены следующие изменения:
Файл
AndroidSourceSet.jniне работал.AndroidSourceSet.wearAppConfigurationName, в связи с удаленной поддержкой встроенного приложения Wear OS.BuildType.isRenderscriptDebuggable, потому что он не работал.DependencyVariantSelection. Он заменяется наDependencySelection, который доступен какkotlin.android.localDependencySelectionInstallation.installOptions(String). Оно заменяется изменяемым свойствомInstallation.installOptions.Экспериментальный, но так и не стабилизированный блок
PostProcessing.ProductFlavor.setDimensionзаменяется свойствомdimension.LanguageSplitOptions, который был полезен только для Google Play Instant , устарел.DensitySplit, поскольку эта функция больше не поддерживается. В качестве замены можно использовать App Bundles .
Удалённые API
В плагине Android Gradle версии 9.0 удалены следующие изменения:
AndroidComponentsExtension.finalizeDSl. Он заменяется наfinalizeDslComponent.transformClassesWith. Он заменяется наInstrumentation.transformClassesWithComponent.setAsmFramesComputationMode. Заменяется наInstrumentation.setAsmFramesComputationModeComponentBuilder.enabled. Заменяется наComponentBuilder.enable.DependenciesInfoBuilder.includedInApkзаменяется наincludeInApkDependenciesInfoBuilder.includedInBundleзаменяется наincludeInBundle.GeneratesApk.targetSdkVersionзаменяется наtargetSdkVariant.minSdkVersionзаменяется наminSdkVariant.maxSdkVersionзаменяется наmaxSdkVariant.targetSdkVersionзаменяется наtargetSdkVariant.unitTest, поскольку он не был применим к плагинуcom.android.test.unitTestдоступен для подтиповVariantBuilder, расширяющихHasUnitTest.VariantBuilder.targetSdkиtargetSdkPreviewне имели смысла в библиотеках. Вместо них используйтеGeneratesApkBuilder.targetSdkилиGeneratesApkBuilder.targetSdkPreview.VariantBuilder.enableUnitTestбыл недоступен для плагинаcom.android.test.enableUnitTestдоступен для подтиповVariantBuilderнаследующихHasUnitTestBuilder.VariantBuilder.unitTestEnabledудален в пользу более согласованного по названиюenableUnitTestв подтипахVariantBuilderнаследующихHasUnitTestBuilder.VariantOutput.enableзаменяется наenabled.Устаревшие и отключенные
FeaturePluginиFeatureExtension.Устаревшие и отключенные API-интерфейсы
BaseExtension.registerTransform, которые остались только для обеспечения возможности компиляции с использованием последней версии AGP при работе на AGP 4.2 или ниже.
Удалены свойства Gradle
Следующие свойства Gradle были первоначально добавлены для глобального отключения функций, которые были включены по умолчанию.
Эти функции отключены по умолчанию начиная с AGP 8.0 и ниже. Для более эффективной сборки включайте эти функции только в тех подпроектах, которые их используют.
| Свойство | Функция | Замена |
|---|---|---|
android. defaults. buildfeatures. aidl | Включает компиляцию AIDL во всех подпроектах. | Разрешите компиляцию AIDL только в тех подпроектах, где есть исходные файлы AIDL, установив следующее свойство в файлах сборки Gradle этих проектов:android {
buildFeatures {
aidl = true
}
} |
android. defaults. buildfeatures. renderscript | Включает компиляцию RenderScript во всех подпроектах. | Разрешите компиляцию RenderScript только в тех подпроектах, где есть исходные файлы RenderScript, установив следующее свойство в файлах сборки Gradle этих проектов: android {
buildFeatures {
renderScript = true
}
} |
Объекты с принудительной регулировкой уровня грунта
В AGP 9.0 возникает ошибка, если задать следующие свойства Gradle.
Плагин Android Gradle Upgrade Assistant не будет обновлять до AGP 9.0 проекты, использующие эти свойства.
| Свойство | Функция |
|---|---|
android. r8. integratedResourceShrinking | Теперь уменьшение объема ресурсов всегда выполняется в рамках R8, предыдущая реализация была удалена. |
android. enableNewResourceShrinker. preciseShrinking | Теперь при сокращении ресурсов всегда используется точное сокращение ресурсов, что позволяет удалять больше ресурсов. |
Изменения в R8
В AGP 9.0.0 включены следующие изменения R8.
Новая опция конфигурации -processkotlinnullchecks
Мы добавили новую опцию R8 -processkotlinnullchecks для настройки R8 на обработку проверок на null в Kotlin. Эта опция принимает обязательный аргумент, который должен принимать одно из следующих трех значений: keep , remove_message и remove . Опция обрабатывает следующие проверки на null, добавленные компилятором Kotlin:
class kotlin.jvm.internal.Intrinsics {
void checkNotNull(java.lang.Object);
void checkNotNull(java.lang.Object, java.lang.String);
void checkExpressionValueIsNotNull(
java.lang.Object, java.lang.String);
void checkNotNullExpressionValue(
java.lang.Object, java.lang.String);
void checkReturnedValueIsNotNull(
java.lang.Object, java.lang.String);
void checkReturnedValueIsNotNull(
java.lang.Object, java.lang.String, java.lang.String);
void checkFieldIsNotNull(java.lang.Object, java.lang.String);
void checkFieldIsNotNull(
java.lang.Object, java.lang.String, java.lang.String);
void checkParameterIsNotNull(java.lang.Object, java.lang.String);
void checkNotNullParameter(java.lang.Object, java.lang.String);
}
Значения опционов, упорядоченные от самого слабого к самому сильному, оказывают следующее воздействие:
-
keepне изменяет результаты проверок. -
remove_messageпереписывает каждый вызов метода проверки на вызов методаgetClass()для первого аргумента вызова (фактически сохраняя проверку на null, но без какого-либо сообщения). -
removeполностью снимает все проверки.
По умолчанию в R8 используется remove_message . Любое указание параметра -processkotlinnullchecks переопределит это значение. Если параметр указан несколько раз, используется наиболее строгое значение.
Прекратите распространение информации о сохранении данных с помощью сопутствующих методов.
Когда правила сохранения соответствуют методам интерфейса, которые подлежат десахаризации, R8 предварительно внутренне передавал биты запрета оптимизации и запрета сжатия синтезированным сопутствующим методам.
Начиная с AGP 9.0, правила сохранения больше не применяются к сопутствующим методам. Это соответствует тому факту, что правила сохранения не применяются к другим полям/методам/классам, синтезируемым компилятором.
Благодаря переносу функций запрета оптимизации и запрета уменьшения битов в сопутствующие методы, ранее поддерживался следующий вариант использования:
- Скомпилируйте библиотеку с методами интерфейса
default/static/privateметодами в DEX сminSdk< 24 и правилами, которые сохраняют методы интерфейса. - Скомпилируйте приложение, добавив библиотеку в classpath и
-applymapping. - Объедините приложение и библиотеку.
Обратите внимание, что это работает только с -applymapping поскольку бит disallow obfuscation не передается на сопутствующие методы — то есть, сопутствующие классы, сгенерированные на шаге 1, будут иметь обфусцированные имена методов.
В дальнейшем этот вариант использования больше не поддерживается для minSdk < 24. В качестве обходного пути можно выполнить следующие действия:
- Десахаризация библиотеки с методами интерфейса
default/static/privateметодами в файлах классов сminSdk< 24. - Скомпилируйте десахаризованный артефакт, используя R8 и правила, которые сохраняют методы интерфейса в сопутствующих классах.
- Скомпилируйте приложение, добавив библиотеку в classpath.
- Объедините приложение и десахаризованный артефакт.
Ещё одним побочным эффектом этого является невозможность сохранения атрибутов внутреннего класса и объемлющего метода для анонимных и локальных классов внутри сопутствующих методов интерфейса.
Измените исходный файл, генерируемый по умолчанию, на r8-map-id-<MAP_ID>
Это изменение внесено в AGP начиная с версии 8.12.0.
Атрибут исходного файла, генерируемого по умолчанию для класса, изменяется с SourceFile на r8-map-id-<MAP_ID> когда требуется трассировка (то есть, когда включено обфускация или оптимизация).
При наличии зашифрованного трассировочного стека новый атрибут исходного файла позволяет извлечь идентификатор файла сопоставления, необходимого для повторной трассировки, что может быть использовано для поддержки автоматической повторной трассировки трассировочных стеков в Logcat .
Если используется пользовательский атрибут исходного файла ( -renamesourcefileattribute ), этот пользовательский атрибут исходного файла продолжает иметь приоритет.
In ProGuard compatibility mode (when gradle.properties contains android.enableR8.fullMode=false ), emitting a source file attribute of r8-map-id-<MAP_ID> only takes effect if the SourceFile attribute is not kept. Apps that use ProGuard compatibility mode and want to include the mapping file ID in their stack traces should remove -keepattributes SourceFile (or migrate to R8 full mode).
В r8-map-id-<MAP_ID> используется полный хеш карты, а не 7-символьный префикс хеша карты, который использовался ранее.
Разрешить использование сокращенных синтетических названий при десахарировании L8.
Имена синтетических классов, генерируемых D8, обычно содержат подстроку $$ExternalSynthetic которая указывает на то, что это синтетический класс, сгенерированный D8. Более того, имя синтетического класса также кодирует его тип (например, Backport , Lambda ). Это негативно влияет на размер результирующего DEX-файла, поскольку имена классов занимают больше места в пуле строк.
AGP 9.0 настраивает L8 (десахаризацию основной библиотеки) таким образом, что DEX-файл, содержащий все классы j$ использует новый сокращенный формат имен классов для синтетических классов. Новое имя класса использует числовой идентификатор (например, $1 ).
Удалена поддержка параметра -addconfigurationdebugging
В AGP 9.0 удалена поддержка флага -addconfigurationdebugging . Теперь компилятор выдает предупреждение, если этот флаг используется.
Удалить поддержку генерации правил L8 из D8/R8
Это изменение актуально только для разработчиков, использующих командную строку D8/R8 или API напрямую.
В версии R8 9.0 удалена поддержка генерации правил сохранения для L8 из D8 и R8. Вместо этого для этой цели следует использовать TraceReferences .
В частности, методы D8Command.builder.setDesugaredLibraryKeepRuleConsumer и R8Command.Builder.setDesugaredLibraryKeepRuleConsumer удалены, а поддержка параметра --desugared-lib-pg-conf-output удалена из параметров командной строки D8 и R8.
Исправлены ошибки
Android Gradle plugin 9.0.0
| Исправлены ошибки | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Плагин Android Gradle |
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Ворс |
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Интеграция Lint |
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Shrinker (R8) |
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Android Gradle plugin 9.0 is a major release that brings API and behavior changes.
To update to Android Gradle plugin 9.0.1, use the Android Gradle plugin Upgrade Assistant . The AGP upgrade assistant helps preserve existing behaviors when upgrading your project whenever appropriate, so you can upgrade your project to use AGP 9.0 even if you're not ready to adopt all the new defaults in AGP 9.0.
There are also two agent skills available to make the upgrade process easier. For a non-KMP app, try the AGP 9 upgrade skill from the Android skills repository. For a KMP app, try the AGP 9 upgrade skill from JetBrains. For more information about using skills in Android Studio, see Extend Agent Mode with skills .
Совместимость
The maximum API level that Android Gradle plugin 9.0 supports is API level 36.1. Here is other compatibility info:
| Минимальная версия | Версия по умолчанию | Примечания | |
|---|---|---|---|
| Грэдл | 9.1.0 | 9.1.0 | To learn more, see updating Gradle . |
| SDK Build Tools | 36.0.0 | 36.0.0 | Install or configure SDK Build Tools. |
| НДК | Н/Д | 28.2.13676358 | Install or configure a different version of the NDK. |
| JDK | 17 | 17 | To learn more, see setting the JDK version . |
The android DSL classes now only implement the new public interfaces
Over the last several years, we have introduced new interfaces for our DSL and API in order to better control which APIs are public. AGP versions 7.x and 8.x still used the old DSL types (for example BaseExtension ) which also implemented the new public interfaces, in order to maintain compatibility as work progressed on the interfaces.
AGP 9.0 uses our new DSL interfaces exclusively, and the implementations have changed to new types that are fully hidden. This also removes access to the old, deprecated variant API.
To update to AGP 9.0, you might need to do the following:
- Ensure your project is compatible with built-in Kotlin : The
org.jetbrains.kotlin.androidplugin is not compatible with the new DSL. Switch KMP projects to the Android Gradle Library Plugin for KMP : Using the
org.jetbrains.kotlin.multiplatformplugin in the same Gradle subproject as thecom.android.libraryandcom.android.applicationplugins is not compatible with the new DSL.Update your build files: While the change of interfaces is meant to keep the DSL as similar as possible, there might be some small changes .
Update your custom build logic to reference the new DSL and API: Replace any references to the internal DSL with the public DSL interfaces. In most cases this will be a one-to-one replacement. Replace any use of the
applicationVariantsand similar APIs with the newandroidComponentsAPI . This might be more complex, as theandroidComponentsAPI is designed to be more stable to keep plugins compatible longer. Check our Gradle Recipes for examples.Update third-party plugins: Some third-party plugins might still depend on interfaces or APIs that are no longer exposed. Migrate to versions of those plugins which are compatible with AGP 9.0.
The switch to the new DSL interfaces prevents plugins and Gradle build scripts using various deprecated APIs, including:
Deprecated API in the android block | Функция | Замена |
|---|---|---|
applicationVariants ,libraryVariants ,testVariants , andunitTestVariants | Extension points for plugins to add new functionality to AGP. | Replace this with the androidComponents.onVariants API, for example:androidComponents { onVariants() { variant -> variant.signingConfig .enableV1Signing.set(false) } } |
variantFilter | Allows selected variants to be disabled. | Replace this with the androidComponents.beforeVariants API, for example: androidComponents { beforeVariants( selector() .withBuildType("debug") .withFlavor("color", "blue") ) { variantBuilder -> variantBuilder.enable = false } } |
deviceProvider andtestServer | Registration of custom test environments for running tests against Android devices and emulators. | Switch to Gradle-managed devices . |
sdkDirectory ,ndkDirectory ,bootClasspath ,adbExecutable , andadbExe | Using various components of the Android SDK for custom tasks. | Switch to androidComponents.sdkComponents . |
registerArtifactType ,registerBuildTypeSourceProvider ,registerProductFlavorSourceProvider ,registerJavaArtifact ,registerMultiFlavorSourceProvider , andwrapJavaSourceSet | Obsolete functionality mostly related to the handling of generated sources in Android Studio, which stopped working in AGP 7.2.0. | There is no direct replacement for these APIs. |
dexOptions | Obsolete settings related to the dx tool, which has been replaced by d8 . None of the settings have had any effect since Android Gradle plugin 7.0. | There is no direct replacement. |
generatePureSplits | Generate configuration splits for instant apps. | The ability to ship configuration splits is now built in to Android app bundles. |
aidlPackagedList | AIDL files to package in the AAR to expose it as API for libraries and apps that depend on this library. | This is still exposed on LibraryExtension but not on the other extension types. |
If you update to AGP 9.0 and see the following error message, it means that your project is still referencing some of the old types:
java.lang.ClassCastException: class com.android.build.gradle.internal.dsl.ApplicationExtensionImpl$AgpDecorated_Decorated
cannot be cast to class com.android.build.gradle.BaseExtension
If you are blocked by incompatible third-party plugins, you can opt out and get back the old implementations for the DSL, as well as the old variant API. While doing this, the new interfaces are also available, and you can still update your own build logic to the new API. To opt out, include this line in your gradle.properties file:
android.newDsl=false
Alternatively, for a more gradual migration, AGP 9.4 lets you opt out individual modules. To learn how, see Variant API module opt-out .
The previous classes are marked as deprecated in AGP 9.0. This means projects that opt out of the newDsl flag will see deprecation warnings, including on the android block itself.
You can also start upgrading to the new APIs before upgrading to AGP 9.0. The new interfaces have been present for many AGP versions and so you can have a mix of new and old. The AGP API reference docs show the API surface for each AGP version, and when each class, method and field was added.
We're reaching out to the authors of commonly used plugins to help them adapt and release plugins that are fully compatible with the new modes, and will continue to enhance the AGP Upgrade Assistant in Android Studio to guide you through the migration.
If you find that the new DSL or Variant API are missing capabilities or features, please file an issue as soon as possible.
Built-in Kotlin
Android Gradle plugin 9.0 introduces built-in Kotlin support and enables it by default. That means you no longer have to apply the org.jetbrains.kotlin.android (or kotlin-android ) plugin in your build files to compile Kotlin source files. This simplifies the Kotlin integration with AGP, avoids the use of deprecated APIs, and improves performance in some cases.
Therefore, when you upgrade your project to AGP 9.0, you need to also migrate to built-in Kotlin or opt out .
You can also selectively disable built-in Kotlin support for Gradle subprojects that don't have Kotlin sources.
Runtime dependency on Kotlin Gradle plugin
To provide built-in Kotlin support, Android Gradle plugin 9.0 now has a runtime dependency on Kotlin Gradle plugin (KGP) 2.2.10. That means you no longer have to declare a KGP version, and if you use a KGP version lower than 2.2.10, Gradle will automatically upgrade your KGP version to 2.2.10. Likewise, if you use a KSP version lower than 2.2.10-2.0.2, AGP will upgrade it to 2.2.10-2.0.2 to match the KGP version.
Upgrade to a higher KGP version
To use a higher version of KGP or KSP, add the following to your top-level build file:
buildscript {
dependencies {
// For KGP
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:KGP_VERSION")
// For KSP
classpath("com.google.devtools.ksp:symbol-processing-gradle-plugin:KSP_VERSION")
}
}
Downgrade to a lower KGP version
You can only downgrade the KGP version if you've opted out of built-in Kotlin . This is because AGP 9.0 enables built-in Kotlin by default, and built-in Kotlin requires KGP 2.2.10 or higher.
To use a lower version of KGP or KSP, declare that version in your top-level build file using a strict version declaration:
buildscript {
dependencies {
// For KGP
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin") {
version { strictly("KGP_VERSION") }
}
// For KSP
classpath("com.google.devtools.ksp:symbol-processing-gradle-plugin") {
version { strictly("KSP_VERSION") }
}
}
}
Note that the minimum KGP version you can downgrade to is 2.0.0.
IDE support for test fixtures
AGP 9.0 brings full Android Studio IDE support for test fixtures .
Fused Library Plugin
The Fused Library Plugin (Preview) lets you publish multiple libraries as a single Android Library AAR. This can make it easier for your users to depend on your published artifacts.
For information about getting started, see Publish multiple Android libraries as one with Fused Library .
Изменения в поведении
Android Gradle plugin 9.0 has the following new behaviors:
| Поведение | Рекомендация |
|---|---|
Android Gradle plugin 9.0 uses NDK version r28c by default. | Consider specifying the NDK version you want to use explicitly. |
| Android Gradle plugin 9.0 by default requires consumers of a library to use the same or higher compile SDK version. | Use the same or higher compile SDK when consuming a library. If this is not possible, or you want to give consumers of a library you publish more time to switch, set AarMetadata.minCompileSdk explicitly. |
AGP 9.0 includes updates to the following Gradle properties' defaults. This gives you the choice to preserve the AGP 8.13 behavior when upgrading:
| Свойство | Функция | Change from AGP 8.13 to AGP 9.0 | Рекомендация |
|---|---|---|---|
android. newDsl | Use the new DSL interfaces, without exposing the legacy implementations of the android block.This also means the legacy variant API, such as android.applicationVariants is no longer accessible. | false → true | You can opt out by setting android.newDsl=false .Once all plugins and build logic your project uses are compatible, remove the opt out. |
android. builtInKotlin | Enables built-in Kotlin | false → true | Migrate to built-in Kotlin if you can or opt out . |
android. uniquePackage Names | Enforces that each library has a distinct package name. | false → true | Specify unique package names for all libraries within your project. If that is not possible, you can disable this flag while you migrate. |
android. useAndroidx | Use androidx dependencies by default. | false → true | Adopt androidx dependencies. |
android. default. androidx. test. runner | Run on-device tests with the androidx.test.runner.AndroidJUnitRunner class by default, replacing the default of the deprecated InstrumentationTestRunner for android {
defaultConfig {
testInstrumentationRunner = "..."
}
} | false → true | Adopt AndroidJUnitRunner , or specify your custom testInstrumentationRunner explicitly. |
android. dependency. useConstraints | Controls the use of dependency constraints between configurations. The default in AGP 9.0 is false which only uses constraints in application device tests (AndroidTest). Setting this to true will revert back to the 8.13 behavior. | true → false | Don't use dependency constraints everywhere unless you need them. Accepting the new default of this flag also enables optimizations in the project import process which should reduce the import time for builds with many Android library subprojects. |
android. enableApp CompileTime RClass | Compile code in applications against a non-final R class, bringing application compilation in line with library compilation. This improves incrementality and paves the way for future performance optimizations to the resource processing flow. | false → true | Many projects can just adopt the new behavior with no source changes. If the R class fields are used anywhere that requires a constant, such as switch cases, refactor to use chained if statements. |
android. sdk. defaultTargetSdk ToCompileSdk IfUnset | Uses the compile SDK version as the default value for the target SDK version in apps and tests. Before this change, the target SDK version would default to the min SDK version. | false → true | Specify the target SDK version explicitly for apps and tests. |
android. onlyEnableUnitTest ForTheTested BuildType | Only creates unit test components for the tested build type. In the default project this results in a single unit test for debug, where the previous behavor was to have unit tests run for debug or release. | false → true | If your project doesn't require tests to run for both debug and release, no change is required. |
android. proguard. failOnMissingFiles | Fails the build with an error if any of the keep files specified in the AGP DSL don't exist on disk. Before this change typos in filenames would result in files being silently ignored. | false → true | Remove any invalid proguard files declarations |
android. r8. optimizedResourceShrinking | Allows R8 to keep fewer Android resources by considering classes and Android resources together. | false → true | If your project's keep rules are already complete, no change is required. |
android. r8. strictFullMode ForKeepRules | Allows R8 to keep less by not implicitly keeping the default constructor when a class is kept. That is, -keep class A no longer implies -keep class A { <init>(); } | false → true | If your project's keep rules are already complete, no change is required. Replace -keep class A with -keep class A { <init>(); } in your project's keep rules for any cases where you need the default constructor to be kept. |
android. defaults. buildfeatures. resvalues | Enables resValues in all subprojects | true → false | Enable resValues in only the subprojects that need it by setting the following in those projects' Gradle build files: android {
buildFeatures {
resValues = true
}
} |
android. defaults. buildfeatures. shaders | Enables shader compilation in all subprojects | true → false | Enable shader compilation in only the subprojects that contain shaders to be compiled by setting the following in those projects' Gradle build files: android {
buildFeatures {
shaders = true
}
} |
android. r8. proguardAndroidTxt. disallowed | In AGP 9.0, getDefaultProguardFile() will only support proguard-android-optimize.txt rather than proguard-android.txt . This is to prevent accidental usage of the dontoptimize flag, which is included in proguard-android.txt . | false → true | You can explicitly specify dontoptimize in a custom proguardFile if you want to avoid optimization, alongside using proguard-android-optimize.txt . Make sure to remove the dontoptimize flag from this file if possible, as it reduces R8 optimization benefits. If not, opt out by setting android.r8.globalOptionsInConsumerRules.disallowed=false . |
android. r8. globalOptions InConsumerRules. disallowed | From AGP 9.0, Android library and feature module publishing will fail if consumer keep files contain problematic Proguard configurations. Consumer keep files that include global options like dontoptimize or dontobfuscate should only be used in application modules, and can reduce optimization benefits for library users. Android App module compilation will silently ignore any such global options if embedded in a pre-compiled dependency (JAR or AAR). You can see when this occurs by checking configuration.txt (typically in a path like <app_module>/build/outputs/mapping/<build_variant>/configuration.txt ) for comments like: # REMOVED CONSUMER RULE: dontoptimize | false → true | Published libraries should remove any incompatible rules. Internal libraries should move any incompatible but required rules to a proguardFile in an app module instead. Opt out by setting android.r8.globalOptionsInConsumerRules.disallowed=false . Once all your consumer keep files are compatible, remove the opt out. |
android. sourceset. disallowProvider | Disallow passing providers for generated sources using the AndroidSourceSet DSL. | false → true | Use the Sources API on androidComponents to register generated sources. |
android. custom. shader. path. required | Requires the shader compiler path to be explicitly set in local.properties if shader compilation is enabled. | false → true | Add glslc.dir=/path/to/shader-tools to your project's local.properties . |
Удалённые функции
Android Gradle plugin 9.0 removes the following functionality:
- Embedded Wear OS app support
AGP 9.0 removes support for embedding Wear OS apps, which is no longer supported in Play. This includes removing thewearAppconfigurations and theAndroidSourceSet.wearAppConfigurationNameDSL. See Distribute to Wear OS for how to publish your app to Wear OS. -
androidDependenciesandsourceSetsreport task - Density split APK support
AGP 9.0 removes support for creating split APKs based on screen density. The functionality and the related APIs have been removed. To split APKs based on screen density using AGP 9.0 or higher, use app bundles .
Changed DSL
Android Gradle plugin 9.0 has the following breaking DSL changes:
The parameterization of
CommonExtensionhas been removed.In itself, this is only a source-level breaking change to help avoid future source-level breaking changes, but it also means that the block methods need to move from
CommonExtensiontoApplicationExtension,LibraryExtension,DynamicFeatureExtensionandTestExtension.When upgrading your project to AGP 9.0, refactor Gradle plugin code which uses those parameters or the block methods. For example the following plugin is updated to remove the type parameter and not rely on the removed block methods:
AGP 8.13
val commonExtension: CommonExtension<*, *, *, *, *, *> = extensions.getByType(CommonExtension::class) commonExtension.apply { defaultConfig { minSdk { version = release(28) } } }AGP 9.0
val commonExtension: CommonExtension = extensions.getByType(CommonExtension::class) commonExtension.apply { defaultConfig.apply { minSdk { version = release(28) } } }For plugins which target a range of AGP versions, using the getter directly is binary compatible with AGP versions lower than 9.0.
Removed DSL
Android Gradle plugin 9.0 removes:
AndroidSourceSet.jni, because it was not functional.AndroidSourceSet.wearAppConfigurationName, as it relates to the removed embedded Wear OS app support.BuildType.isRenderscriptDebuggable, because it was not functional.DependencyVariantSelection. It is replaced ByDependencySelection, which is exposed askotlin.android.localDependencySelectionInstallation.installOptions(String). It is replaced by the mutable property ofInstallation.installOptions.The experimental, but never stabilized
PostProcessingblock.ProductFlavor.setDimension, which is replaced by thedimensionpropertyLanguageSplitOptions, which was only useful for Google Play Instant , which is deprecated.DensitySplit, because the feature is no longer supported. Replacement is to use App Bundles .
Удалённые API
Android Gradle plugin 9.0 removes:
AndroidComponentsExtension.finalizeDSl. It is replaced byfinalizeDslComponent.transformClassesWith. It is replaced byInstrumentation.transformClassesWithComponent.setAsmFramesComputationMode. It is replaced byInstrumentation.setAsmFramesComputationModeComponentBuilder.enabled. It is replaced byComponentBuilder.enable.DependenciesInfoBuilder.includedInApk. Is is replaced byincludeInApkDependenciesInfoBuilder.includedInBundle. Is is replaced byincludeInBundleGeneratesApk.targetSdkVersion. Is is replaced bytargetSdkVariant.minSdkVersion. Is is replaced byminSdkVariant.maxSdkVersion. Is is replaced bymaxSdkVariant.targetSdkVersion. Is is replaced bytargetSdkVariant.unitTest, as it was not applicable to thecom.android.testplugin.unitTestis available onVariantBuildersubtypes extendingHasUnitTest.VariantBuilder.targetSdkandtargetSdkPreview, as they were not meaningful in libraries. UseGeneratesApkBuilder.targetSdkorGeneratesApkBuilder.targetSdkPreviewinstead.VariantBuilder.enableUnitTest, as it was not applicable to thecom.android.testplugin.enableUnitTestis available onVariantBuildersubtypes extendingHasUnitTestBuilder.VariantBuilder.unitTestEnabledis removed in favor of the more consistently namedenableUnitTeston theVariantBuildersubtypes extendingHasUnitTestBuilder.VariantOutput.enable. Is is replaced byenabledThe deprecated and disabled
FeaturePluginandFeatureExtension.The deprecated and disabled
BaseExtension.registerTransformAPIs, which only remained to allow compiling against the latest AGP version while targeting running on AGP 4.2 or lower.
Removed Gradle properties
The following Gradle properties were initially added as ways to globally disable features that were enabled by default.
These features have been disabled by default since AGP 8.0 or lower. Enable these features in only the sub-projects that use them for a more efficient build.
| Свойство | Функция | Замена |
|---|---|---|
android. defaults. buildfeatures. aidl | Enables AIDL compilation in all subprojects | Enable AIDL compilation in only the subprojects where there are AIDL sources by setting the following property in those projects' Gradle build files:android {
buildFeatures {
aidl = true
}
} |
android. defaults. buildfeatures. renderscript | Enables RenderScript compilation in all subprojects | Enable renderscript compilation in only the subprojects where there are renderscript sources by setting the following property in those projects' Gradle build files: android {
buildFeatures {
renderScript = true
}
} |
Enforced Gradle properties
AGP 9.0 throws an error if you set the following Gradle properties.
The Android Gradle plugin Upgrade Assistant won't upgrade projects to AGP 9.0 that use these properties.
| Свойство | Функция |
|---|---|
android. r8. integratedResourceShrinking | Resource shrinking is now always run as part of R8, the previous implementation has been removed. |
android. enableNewResourceShrinker. preciseShrinking | Resource shrinking now always uses precise resource shrinking, which enables more to be removed. |
R8 changes
The following R8 changes are included in AGP 9.0.0.
New configuration option -processkotlinnullchecks
We've added the new R8 option -processkotlinnullchecks to configure R8 for processing Kotlin null checks. The option takes a mandatory argument that must be one of the following three values: keep , remove_message and remove . The option processes the following null checks added by the Kotlin compiler:
class kotlin.jvm.internal.Intrinsics {
void checkNotNull(java.lang.Object);
void checkNotNull(java.lang.Object, java.lang.String);
void checkExpressionValueIsNotNull(
java.lang.Object, java.lang.String);
void checkNotNullExpressionValue(
java.lang.Object, java.lang.String);
void checkReturnedValueIsNotNull(
java.lang.Object, java.lang.String);
void checkReturnedValueIsNotNull(
java.lang.Object, java.lang.String, java.lang.String);
void checkFieldIsNotNull(java.lang.Object, java.lang.String);
void checkFieldIsNotNull(
java.lang.Object, java.lang.String, java.lang.String);
void checkParameterIsNotNull(java.lang.Object, java.lang.String);
void checkNotNullParameter(java.lang.Object, java.lang.String);
}
The option values, ordered from the weakest to the strongest, have the following effect:
-
keepdoesn't change the checks. -
remove_messagerewrites each check method call to a call togetClass()on the first argument of the call (effectively keeping the null check, but without any message). -
removecompletely removes the checks.
By default R8 uses remove_message . Any specification of -processkotlinnullchecks will override that. If specified multiple times the strongest value is used.
Stop propagating keep info to companion methods
When keep rules match interface methods that are subject to desugaring, R8 previously internally transferred the disallow optimization and disallow shrinking bits to the synthesized companion methods.
Starting with AGP 9.0, keep rules no longer apply to companion methods. This is consistent with the fact that keep rules are not applicable to other compiler synthesized fields/methods/classes.
By transferring the disallow optimization and disallow shrinking bits to the companion methods, the following use case was previously supported:
- Compile a library with
default/static/privateinterface methods to DEX withminSdk< 24 and rules that keep the interface methods. - Compile an app with the library on classpath and
-applymapping. - Merge the app and the library.
Note that this only works with -applymapping since the disallow obfuscation bit is not transferred to the companion methods—that is, the companion classes generated from step 1 would have obfuscated method names.
Going forward this use case is no longer supported for minSdk < 24. The workaround is to do the following:
- Desugar the library with
default/static/privateinterface methods to class files withminSdk< 24. - Compile the desugared artifact using R8 and rules that keep the interface methods on the companion classes.
- Compile the app with the library on classpath.
- Merge the app and the desugared artifact.
Another side effect of this is that it is no longer possible to keep the inner class and enclosing method attributes for anonymous and local classes inside interface companion methods.
Change the default emitted source file to r8-map-id-<MAP_ID>
This change is in AGP starting from 8.12.0.
The default emitted source file attribute for a class changes from SourceFile to r8-map-id-<MAP_ID> when retracing is required (that is, when either obfuscation or optimization is enabled).
Given an obfuscated stack trace, the new source file attribute makes it possible to extract the ID of the mapping file that is required for retracing, which can be used to support automated retracing of stack traces in Logcat .
If a custom source file attribute is used ( -renamesourcefileattribute ) this custom source file attribute continues to take precedence.
In ProGuard compatibility mode (when gradle.properties contains android.enableR8.fullMode=false ), emitting a source file attribute of r8-map-id-<MAP_ID> only takes effect if the SourceFile attribute is not kept. Apps that use ProGuard compatibility mode and want to include the mapping file ID in their stack traces should remove -keepattributes SourceFile (or migrate to R8 full mode).
The map ID used in r8-map-id-<MAP_ID> is the full map hash, and not a 7 character prefix of the map hash which was previously used.
Enable use of minimized synthetic names in L8 desugaring
The name of synthetic classes generated by D8 normally contains the substring $$ExternalSynthetic that tells you that this is a synthetic generated by D8. Moreover, the name of the synthetic also encodes the synthetic kind (for example, Backport , Lambda ). This has a negative impact on the resulting DEX size, since the class names take up more space in the string pool.
AGP 9.0 configures L8 (core library desugaring) so that the DEX file containing all j$ classes uses a new shortened class name format for synthetic classes. The new class name uses a numeric ID (for example, $1 ).
Remove support for -addconfigurationdebugging
AGP 9.0 removes support for -addconfigurationdebugging . The compiler now reports a warning if the flag is used.
Remove support for generating L8 rules from D8/R8
This change is only relevant for developers using the D8/R8 command line or APIs directly.
R8 9.0 removes support for generating keep rules for L8 from D8 and R8. You should instead use TraceReferences for this purpose.
More specifically, the methods D8Command.builder.setDesugaredLibraryKeepRuleConsumer and R8Command.Builder.setDesugaredLibraryKeepRuleConsumer are removed, and the support for --desugared-lib-pg-conf-output is removed from the command line options of D8 and R8.
Исправлены ошибки
Android Gradle plugin 9.0.0
| Исправлены ошибки | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Плагин Android Gradle |
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Ворс |
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Lint Integration |
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Shrinker (R8) |
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||