Migrer vers le plug-in de bibliothèque Android-KMP
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Kotlin Multiplatform dispose d'un plug-in Gradle pour configurer le module de bibliothèque.
Le plug-in com.android.kotlin.multiplatform.library remplace officiellement l'ancienne méthode d'ajout de cibles Android aux bibliothèques KMP à l'aide du plug-in Gradle de bibliothèque Android standard (com.android.library).
L'approche précédente est désormais obsolète au profit du plug-in, également appelé plug-in Android-KMP. L'utilisation du plug-in com.android.library pour KMP ne sera plus prise en charge par JetBrains et ne bénéficiera plus des futures mises à jour et améliorations.
Le plug-in Android-KMP est spécialement conçu pour les projets KMP et diffère du plug-in com.android.library standard sur plusieurs aspects clés :
Architecture à variante unique : le plug-in utilise une seule variante, ce qui supprime la prise en charge des types de produit et des types de compilation. La configuration est ainsi simplifiée et les performances de compilation améliorées.
Optimisé pour KMP : le plug-in est conçu pour les bibliothèques KMP. Il se concentre sur le code Kotlin partagé et l'interopérabilité, et ne prend pas en charge les compilations natives spécifiques à Android, AIDL et RenderScript.
Tests désactivés par défaut : les tests unitaires et les tests d'instrumentation (sur l'appareil) sont désactivés par défaut pour améliorer la vitesse de compilation. Vous pouvez les activer si nécessaire.
Pas d'extension Android de premier niveau : la configuration est gérée avec un bloc androidLibrary dans le DSL Gradle KMP, ce qui permet de maintenir une structure de projet KMP cohérente. Aucun blocage d'extension android de premier niveau n'est défini.
Compilation Java activée : la compilation Java est désactivée par défaut. Pour l'activer, utilisez withJava() dans le bloc androidLibrary. Cela permet d'améliorer les temps de compilation lorsque la compilation Java n'est pas nécessaire.
Avantages du plug-in de bibliothèque Android-KMP
Le plug-in Android-KMP offre les avantages suivants pour les projets KMP :
Amélioration des performances et de la stabilité de la compilation : elle est conçue pour optimiser la vitesse de compilation et améliorer la stabilité dans les projets KMP. L'accent mis sur les workflows KMP contribue à un processus de compilation plus efficace et fiable.
Intégration IDE améliorée : elle offre une meilleure saisie semi-automatique du code, une meilleure navigation, un meilleur débogage et une meilleure expérience globale pour les développeurs lorsqu'ils travaillent avec les bibliothèques KMP Android.
Configuration de projet simplifiée : le plug-in simplifie la configuration des projets KMP en supprimant les complexités spécifiques à Android, comme les variantes de compilation. Cela permet d'obtenir des fichiers de compilation plus clairs et plus faciles à gérer.
Auparavant, l'utilisation du plug-in com.android.library dans un projet KMP pouvait créer des noms de source set déroutants, tels que androidAndroidTest. Cette convention de dénomination était moins intuitive pour les développeurs connaissant les structures de projet KMP standards.
Appliquer le plug-in Android-KMP à un module existant
Pour appliquer le plug-in Android-KMP à un module de bibliothèque KMP existant, procédez comme suit :
Déclarez les plug-ins dans le catalogue de versions. Ouvrez le fichier TOML du catalogue de versions (généralement gradle/libs.versions.toml) et ajoutez la section des définitions de plug-in :
# To check the version number of the latest Kotlin release, go to# https://kotlinlang.org/docs/releases.html[versions]androidGradlePlugin="8.12.0"kotlin="KOTLIN_VERSION"[plugins]kotlin-multiplatform={id="org.jetbrains.kotlin.multiplatform",version.ref="kotlin"}android-kotlin-multiplatform-library={id="com.android.kotlin.multiplatform.library",version.ref="androidGradlePlugin"}
Appliquez la déclaration du plug-in dans le fichier de compilation racine. Ouvrez le fichier build.gradle.kts situé dans le répertoire racine de votre projet. Ajoutez les alias de plug-in au bloc plugins à l'aide de apply false. Cela rend les alias de plug-in disponibles pour tous les sous-projets sans appliquer la logique du plug-in au projet racine lui-même.
Kotlin
// Root build.gradle.kts fileplugins{alias(libs.plugins.kotlin.multiplatform)applyfalse// Add the followingalias(libs.plugins.android.kotlin.multiplatform.library)applyfalse}
Groovy
// Root build.gradle fileplugins{alias(libs.plugins.kotlin.multiplatform)applyfalse// Add the followingalias(libs.plugins.android.kotlin.multiplatform.library)applyfalse}
Appliquez le plug-in dans un fichier de compilation de module de bibliothèque KMP. Ouvrez le fichier build.gradle.kts dans votre module de bibliothèque KMP et appliquez le plug-in en haut de votre fichier dans le bloc plugins :
Kotlin
// Module-specific build.gradle.kts fileplugins{alias(libs.plugins.kotlin.multiplatform)// Add the followingalias(libs.plugins.android.kotlin.multiplatform.library)}
Groovy
// Module-specific build.gradle fileplugins{alias(libs.plugins.kotlin.multiplatform)// Add the followingalias(libs.plugins.android.kotlin.multiplatform.library)}
Configurez la cible Android KMP. Configurez le bloc Kotlin Multiplatform (kotlin) pour définir la cible Android. Dans le bloc kotlin, spécifiez la cible Android à l'aide de androidLibrary :
Appliquez les modifications. Après avoir appliqué le plug-in et configuré le bloc kotlin, synchronisez votre projet Gradle pour appliquer les modifications.
Recommandations personnalisées
Remarque : Le texte du lien s'affiche lorsque JavaScript est désactivé
Le contenu et les exemples de code de cette page sont soumis aux licences décrites dans la Licence de contenu. Java et OpenJDK sont des marques ou des marques déposées d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/08/21 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Il n'y a pas l'information dont j'ai besoin","missingTheInformationINeed","thumb-down"],["Trop compliqué/Trop d'étapes","tooComplicatedTooManySteps","thumb-down"],["Obsolète","outOfDate","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Mauvais exemple/Erreur de code","samplesCodeIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/08/21 (UTC)."],[],[],null,["# Migrate to the Android-KMP library plugin\n\nKotlin Multiplatform has a Gradle plugin to configure the\n[library module](/studio/projects/android-library).\n\nThe `com.android.kotlin.multiplatform.library` plugin is the official\nreplacement for the previous method of adding Android targets to KMP libraries\nusing the regular Android library Gradle plugin (`com.android.library`).\n\nThe previous approach is now deprecated in favor of the plugin, also referred to\nas the **Android-KMP plugin** . Continuing to use the `com.android.library`\nplugin for KMP will no longer be supported by JetBrains and won't benefit from\nfuture updates and improvements.\n| **Note:** Configuring the Android **application** module using `com.android.application` doesn't change.\n\nTo migrate to this plugin, refer to the [Apply the Android-KMP plugin](#apply)\nsection.\n\nKey features and differences\n----------------------------\n\nThe Android-KMP plugin is tailored specifically for KMP projects and differs\nfrom the standard `com.android.library` plugin in several key aspects:\n\n- **Single variant architecture:** The plugin uses a single variant, removing\n support for product flavors and build types, which simplifies configuration\n and enhances build performance.\n\n- **Optimized for KMP:** The plugin is designed for KMP libraries, focusing on\n shared Kotlin code and interoperability, omitting support for\n Android-specific native builds, AIDL, and RenderScript.\n\n- **Tests disabled by default:** Both unit and device (instrumentation) tests\n are disabled by default to enhance build speed. You can enable them if\n required.\n\n- **No top-Level Android extension:** Configuration is handled with an\n `androidLibrary` block within the Gradle KMP DSL, maintaining a consistent\n KMP project structure. There's no top-level `android` extension block.\n\n- **Opt-in Java compilation:** Java compilation is disabled by default. Use\n `withJava()` in the `androidLibrary` block to enable it. This improves build\n times when Java compilation is not needed.\n\nBenefits of the Android-KMP library plugin\n------------------------------------------\n\nThe Android-KMP plugin provides the following benefits for KMP projects:\n\n- **Improved build performance and stability:** It's engineered for optimized\n build speeds and enhanced stability within KMP projects. It's focus on KMP\n workflows contribute to a more efficient and reliable build process.\n\n- **Enhanced IDE integration:** It provides better code completion,\n navigation, debugging, and overall developer experience when working with\n KMP Android libraries.\n\n- **Simplified project configuration:** The plugin simplifies configuration\n for KMP projects by removing Android-specific complexities like build\n variants. This leads to cleaner and more maintainable build files.\n Previously, using the `com.android.library` plugin in KMP project could\n create confusing source set names, such as `androidAndroidTest`. This naming\n convention was less intuitive for developers familiar with standard KMP\n project structures.\n\nApply the Android-KMP plugin to an existing module\n--------------------------------------------------\n\nTo apply the Android-KMP plugin to an existing KMP library module, follow these\nsteps:\n\n1. **Declare plugins in version catalog.** Open the version catalog TOML file\n (usually `gradle/libs.versions.toml`) and add the plugin definitions\n section:\n\n # To check the version number of the latest Kotlin release, go to\n # https://kotlinlang.org/docs/releases.html\n\n [versions]\n androidGradlePlugin = \"8.12.0\"\n kotlin = \"\u003cvar translate=\"no\"\u003eKOTLIN_VERSION\u003c/var\u003e\"\n\n [plugins]\n kotlin-multiplatform = { id = \"org.jetbrains.kotlin.multiplatform\", version.ref = \"kotlin\" }\n android-kotlin-multiplatform-library = { id = \"com.android.kotlin.multiplatform.library\", version.ref = \"androidGradlePlugin\" }\n\n2. **Apply the plugin declaration in root build file.** Open the\n `build.gradle.kts` file located in the root directory of your project. Add\n the plugin aliases to the `plugins` block using `apply false`. This makes\n the plugin aliases available to all subprojects without applying the plugin\n logic to the root project itself.\n\n ### Kotlin\n\n ```kotlin\n // Root build.gradle.kts file\n\n plugins {\n alias(libs.plugins.kotlin.multiplatform) apply false\n\n // Add the following\n alias(libs.plugins.android.kotlin.multiplatform.library) apply false\n }\n ```\n\n ### Groovy\n\n ```groovy\n // Root build.gradle file\n\n plugins {\n alias(libs.plugins.kotlin.multiplatform) apply false\n\n // Add the following\n alias(libs.plugins.android.kotlin.multiplatform.library) apply false\n }\n ```\n3. **Apply the plugin in a KMP library module build file.** Open the\n `build.gradle.kts` file in your KMP library module and apply the plugin at\n the top of your file within the `plugins` block:\n\n ### Kotlin\n\n ```kotlin\n // Module-specific build.gradle.kts file\n\n plugins {\n alias(libs.plugins.kotlin.multiplatform)\n\n // Add the following\n alias(libs.plugins.android.kotlin.multiplatform.library)\n }\n ```\n\n ### Groovy\n\n ```groovy\n // Module-specific build.gradle file\n\n plugins {\n alias(libs.plugins.kotlin.multiplatform)\n\n // Add the following\n alias(libs.plugins.android.kotlin.multiplatform.library)\n }\n ```\n4. **Configure Android KMP target.** Configure the Kotlin Multiplatform block\n (`kotlin`) to define the Android target. Within the `kotlin` block, specify\n the Android target using `androidLibrary`:\n\n ### Kotlin\n\n ```kotlin\n kotlin {\n androidLibrary {\n namespace = \"com.example.kmpfirstlib\"\n compileSdk = 33\n minSdk = 24\n\n withJava() // enable java compilation support\n withHostTestBuilder {}.configure {}\n withDeviceTestBuilder {\n sourceSetTreeName = \"test\"\n }\n\n compilations.configureEach {\n compilerOptions.configure {\n jvmTarget.set(\n org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_1_8\n )\n }\n }\n }\n\n sourceSets {\n androidMain {\n dependencies {\n // Add Android-specific dependencies here\n }\n }\n getByName(\"androidHostTest\") {\n dependencies {\n }\n }\n\n getByName(\"androidDeviceTest\") {\n dependencies {\n }\n }\n }\n // ... other targets (JVM, iOS, etc.) ...\n }\n ```\n\n ### Groovy\n\n ```groovy\n kotlin {\n androidLibrary {\n namespace = \"com.example.kmpfirstlib\"\n compileSdk = 33\n minSdk = 24\n\n withJava() // enable java compilation support\n withHostTestBuilder {}.configure {}\n withDeviceTestBuilder {\n it.sourceSetTreeName = \"test\"\n }\n\n compilations.configureEach {\n compilerOptions.options.jvmTarget.set(\n org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_1_8\n )\n }\n }\n\n sourceSets {\n androidMain {\n dependencies {\n }\n }\n androidHostTest {\n dependencies {\n }\n }\n androidDeviceTest {\n dependencies {\n }\n }\n }\n // ... other targets (JVM, iOS, etc.) ...\n }\n ```\n5. **Apply changes.** After applying the plugin and configuring the `kotlin`\n block, sync your Gradle project to apply the changes.\n\nRecommended for you\n-------------------\n\n- Note: link text is displayed when JavaScript is off\n- [Set up your environment](/kotlin/multiplatform/setup)\n- [Add KMP module to a project](/kotlin/multiplatform/migrate)"]]