banner



How To Add Maven Dependency In Android Studio

The Gradle build organisation in Android Studio makes it easy to include external binaries or other library modules to your build as dependencies. The dependencies can exist located on your machine or in a remote repository, and any transitive dependencies they declare are automatically included every bit well. This page describes how to apply dependencies with your Android project, including details about behaviors and configurations that are specific to the Android plugin for Gradle. For a deeper conceptual guide to Gradle dependencies, you should likewise see the Gradle guide for dependency management —only remember that your Android project must use only the dependency configurations defined on this folio.

Dependency types

To add a dependency to your project, specify a dependency configuration such as implementation in the dependencies block of your module'south build.gradle file.

For example, the following build.gradle file for an app module includes three different types of dependencies:

Groovy

plugins {   id 'com.android.application' }  android { ... }  dependencies {     // Dependency on a local library module     implementation projection(':mylibrary')      // Dependency on local binaries     implementation fileTree(dir: 'libs', include: ['*.jar'])      // Dependency on a remote binary     implementation 'com.instance.android:app-magic:12.3' }            

Kotlin

plugins {     id("com.android.application") }  android { ... }  dependencies {     // Dependency on a local library module     implementation(project(":mylibrary"))      // Dependency on local binaries     implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))      // Dependency on a remote binary     implementation("com.case.android:app-magic:12.three") }            

Each of these requests a different kind of library dependency as follows:

Local library module dependency

Groovy

implementation project(':mylibrary')

Kotlin

implementation(project(":mylibrary"))

This declares a dependency on an Android library module named "mylibrary" (this proper noun must match the library name defined with an include: in your settings.gradle file). When yous build your app, the build system compiles the library module and packages the resulting compiled contents in the app.

Local binary dependency

Not bad

                  implementation fileTree(dir: 'libs', include: ['*.jar'])                

Kotlin

                  implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar"))))                

Gradle declares dependencies on JAR files inside your project'due south module_name/libs/ directory (because Gradle reads paths relative to the build.gradle file).

Alternatively, you lot tin specify individual files as follows:

Groovy

                  implementation files('libs/foo.jar', 'libs/bar.jar')                

Kotlin

                  implementation(files("libs/foo.jar", "libs/bar.jar"))                
Remote binary dependency

Peachy

                  implementation 'com.example.android:app-magic:12.3'                

Kotlin

                  implementation("com.example.android:app-magic:12.3")                

This is actually shorthand for the following:

Groovy

                  implementation group: 'com.example.android', name: 'app-magic', version: '12.3'

Kotlin

                  implementation(group = "com.example.android", name = "app-magic", version = "12.iii")

This declares a dependency on version 12.3 of the "app-magic" library, inside the "com.example.android" namespace group.

Notation: Remote dependencies similar this require that you declare the appropriate remote repositories where Gradle should look for the library. If the library does not already exist locally, Gradle pulls it from the remote site when the build requires it (such every bit when you lot click Sync Project with Gradle Files or when yous run a build).

If y'all depend on an AGP dependency at compile-time, make certain to add together it as an explicit dependency. Considering AGP uses api/implementation configurations internally, some artifacts may be removed from your compile classpath and your compile classpath may change.

Native dependencies

As of Android Gradle plugin 4.0, native dependencies can also exist imported in the way described in this certificate.

Depending on an AAR that exposes native libraries volition automatically brand them available to the build system used past externalNativeBuild. To admission the libraries from your code, you must link to them in your native build scripts. In this document, see Using native dependencies.

Dependency configurations

Inside the dependencies cake, you lot can declare a library dependency using ane of several unlike dependency configurations (such equally implementation shown above). Each dependency configuration provides Gradle with different instructions about how to apply the dependency. The following tabular array describes each of the configurations yous tin use for a dependency in your Android project. The tabular array also compares these configurations to those that were deprecated as of Android Gradle plugin 3.0.0.

Configuration Behavior
implementation Gradle adds the dependency to the compile classpath and packages the dependency to the build output. However, when your module configures an implementation dependency, information technology'due south letting Gradle know that you exercise not desire the module to leak the dependency to other modules at compile fourth dimension. That is, the dependency is bachelor to other modules just at runtime.

Using this dependency configuration instead of api or compile (deprecated) can issue in pregnant build fourth dimension improvements because it reduces the number of modules that the build organisation needs to recompile. For case, if an implementation dependency changes its API, Gradle recompiles only that dependency and the modules that directly depend on it. About app and test modules should use this configuration.

api Gradle adds the dependency to the compile classpath and build output. When a module includes an api dependency, information technology's letting Gradle know that the module wants to transitively export that dependency to other modules, so that information technology'southward available to them at both runtime and compile fourth dimension.

This configuration behaves just like compile (which is now deprecated), but you lot should use it with caution and only with dependencies that you need to transitively export to other upstream consumers. That's because, if an api dependency changes its external API, Gradle recompiles all modules that have admission to that dependency at compile time. So, having a big number of api dependencies can significantly increase build time. Unless y'all want to expose a dependency's API to a dissever module, library modules should instead employ implementation dependencies.

compileOnly Gradle adds the dependency to the compile classpath only (that is, it is not added to the build output). This is useful when you're creating an Android module and you need the dependency during compilation, but it's optional to have it present at runtime.

If y'all use this configuration, and then your library module must include a runtime status to cheque whether the dependency is bachelor, then gracefully change its beliefs so information technology can still office if it's not provided. This helps reduce the size of the final app by not adding transient dependencies that aren't critical. This configuration behaves but like provided (which is now deprecated).

Note: You tin't use the compileOnly configuration with AAR dependencies.

runtimeOnly Gradle adds the dependency to the build output only, for utilise during runtime. That is, it is not added to the compile classpath. This configuration behaves just like apk (which is now deprecated).
annotationProcessor

To add a dependency on a library that is an annotation processor, y'all must add it to the notation processor classpath using the annotationProcessor configuration. That's because using this configuration improves build performance by separating the compile classpath from the notation processor classpath. If Gradle finds annotation processors on the compile classpath, it deactivates compile avoidance, which negatively impacts build time (Gradle 5.0 and college ignore note processors found on the compile classpath).

The Android Gradle plugin assumes a dependency is an note processor if its JAR file contains the following file:

META-INF/services/javax.annotation.processing.Processor

If the plugin detects an annotation processor that's on the compile classpath, it produces a build mistake.

Note: Kotlin projects should use kapt to declare annotation processor dependencies.

lintChecks

Use this configuration to include lint checks you want Gradle to execute when edifice your projection.

Note: When using Android Gradle plugin 3.4.0 and higher, this dependency configuration no longer packages the lint checks in your Android Library projects. To include lint bank check dependencies in your AAR libraries, use the lintPublish configuration described below.

lintPublish Employ this configuration in Android library projects to include lint checks yous desire Gradle to compile into a lint.jar file and packet in your AAR. This causes projects that eat your AAR to also employ those lint checks. If you lot were previously using the lintChecks dependency configuration to include lint checks in the published AAR, you demand to migrate those dependencies to instead use the lintPublish configuration.

Groovy

dependencies {   // Executes lint checks from the ':checks' project at build time.   lintChecks project(':checks')   // Compiles lint checks from the ':checks-to-publish' into a   // lint.jar file and publishes it to your Android library.   lintPublish project(':checks-to-publish') }                    

Kotlin

dependencies {   // Executes lint checks from the ":checks" project at build fourth dimension.   lintChecks(project(":checks"))   // Compiles lint checks from the ":checks-to-publish" into a   // lint.jar file and publishes it to your Android library.   lintPublish(project(":checks-to-publish")) }                    

Deprecated Gradle configurations (available in AGP 1.0–4.2)

Configuration Behavior
apk Gradle adds the dependency to the build output only, for utilise during runtime. That is, it is not added to the compile classpath.
compile Gradle adds the dependency to the compile classpath and build output. Exports the dependency to other modules.
provided Gradle adds the dependency to the compile classpath simply (that is, it is not added to the build output).

All of the in a higher place configurations utilise dependencies to all build variants. If you instead want to declare a dependency for only a specific build variant source set or for a testing source set, y'all must capitalize the configuration name and prefix information technology with the name of the build variant or testing source fix.

For example, to add an implementation dependency only to your "gratis" product flavor (using a remote binary dependency), it looks like this:

Keen

dependencies {     freeImplementation 'com.google.firebase:firebase-ads:9.8.0' }            

Kotlin

dependencies {     freeImplementation("com.google.firebase:firebase-ads:nine.8.0") }            

Notwithstanding, if you desire to add a dependency for a variant that combines a production flavor and a build type, then you lot must initialize the configuration proper name in the configurations cake. The post-obit sample adds a runtimeOnly dependency to your "freeDebug" build variant (using a local binary dependency).

Keen

configurations {     // Initializes a placeholder for the freeDebugRuntimeOnly dependency configuration.     freeDebugRuntimeOnly {} }  dependencies {     freeDebugRuntimeOnly fileTree(dir: 'libs', include: ['*.jar']) }            

Kotlin

// Initializes a placeholder for the freeDebugRuntimeOnly dependency configuration. val freeDebugRuntimeOnly past configurations.creating  dependencies {     freeDebugRuntimeOnly(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar")))) }            

To add implementation dependencies for your local tests and instrumented tests , it looks like this:

Bang-up

dependencies {     // Adds a remote binary dependency just for local tests.     testImplementation 'junit:junit:iv.12'      // Adds a remote binary dependency only for the instrumented test APK.     androidTestImplementation 'androidx.examination.espresso:espresso-core:3.0.2' }            

Kotlin

dependencies {     // Adds a remote binary dependency only for local tests.     testImplementation("junit:junit:4.12")      // Adds a remote binary dependency simply for the instrumented test APK.     androidTestImplementation("androidx.test.espresso:espresso-core:iii.0.2") }            

However, certain configurations don't brand sense in this situation. For instance, because other modules tin can't depend on androidTest, you lot become the following warning if y'all use the androidTestApi configuration:

Alert: Configuration 'androidTestApi' is obsolete and has been replaced with 'androidTestImplementation'.        

Add annotation processors

If yous add annotation processors to your compile classpath, you'll come across an error message like to the following:

Mistake: Annotation processors must be explicitly declared now.        

To resolve this fault, add annotation processors to your project by configuring your dependency using annotationProcessor as shown below:

Groovy

dependencies {     // Adds libraries defining annotations to but the compile classpath.     compileOnly 'com.google.dagger:dagger:version-number'     // Adds the annotation processor dependency to the note processor classpath.     annotationProcessor 'com.google.dagger:dagger-compiler:version-number' }            

Kotlin

dependencies {     // Adds libraries defining annotations to just the compile classpath.     compileOnly("com.google.dagger:dagger:version-number")     // Adds the annotation processor dependency to the notation processor classpath.     annotationProcessor("com.google.dagger:dagger-compiler:version-number") }            

Note: Android plugin for Gradle three.0.0+ no longer supports android-apt plugin.

Pass arguments to notation processors

If y'all need to pass arguments to an annotation processor, you can do so using the AnnotationProcessorOptions cake in your module's build configuration. For instance, if you want to laissez passer primitive data types as central-value pairs, you can employ the argument property, as shown below:

Groovy

android {     ...     defaultConfig {         ...         javaCompileOptions {             annotationProcessorOptions {                 argument 'key1', 'value1'                 argument 'key2', 'value2'             }         }     } }            

Kotlin

android {     ...     defaultConfig {         ...         javaCompileOptions {             annotationProcessorOptions {                 arguments += mapOf("key1" to "value1",                                    "key2" to "value2")             }         }     } }            

Nonetheless, when using Android Gradle plugin iii.2.0 and higher, you demand to laissez passer processor arguments that represent files or directories using Gradle's CommandLineArgumentProvider interface.

Using CommandLineArgumentProvider allows y'all or the annotation processor author to ameliorate the correctness and functioning of incremental and cached clean builds by applying incremental build property blazon annotations to each argument.

For instance, the class below implements CommandLineArgumentProvider and annotates each argument for the processor. The sample as well uses the Groovy language syntax and is included directly in the module'southward build.gradle file.

Groovy

class MyArgsProvider implements CommandLineArgumentProvider {      // Annotates each directory as either an input or output for the     // annotation processor.     @InputFiles     // Using this annotation helps Gradle determine which part of the file path     // should exist considered during up-to-date checks.     @PathSensitive(PathSensitivity.RELATIVE)     FileCollection inputDir      @OutputDirectory     File outputDir      // The class constructor sets the paths for the input and output directories.     MyArgsProvider(FileCollection input, File output) {         inputDir = input         outputDir = output     }      // Specifies each directory as a control line argument for the processor.     // The Android plugin uses this method to pass the arguments to the     // annotation processor.     @Override     Iterable<String> asArguments() {         // Use the form '-Akey[=value]' to laissez passer your options to the Coffee compiler.         ["-AinputDir=${inputDir.singleFile.absolutePath}",          "-AoutputDir=${outputDir.absolutePath}"]     } }  android {...}            

Kotlin

class MyArgsProvider(     // Annotates each directory as either an input or output for the     // annotation processor.     @get:InputFiles     // Using this annotation helps Gradle determine which part of the file path     // should exist considered during upward-to-date checks.     @get:PathSensitive(PathSensitivity.RELATIVE)     val inputDir: FileCollection,      @go:OutputDirectory     val outputDir: File ) : CommandLineArgumentProvider {     // Specifies each directory every bit a control line argument for the processor.     // The Android plugin uses this method to laissez passer the arguments to the     // note processor.      override fun asArguments(): Iterable<Cord> {         // Use the form '-Akey[=value]' to pass your options to the Coffee compiler.         render listOf("-AinputDir=${inputDir.singleFile.absolutePath}",                       "-AoutputDir=${outputDir.absolutePath}")     } }  android {...}            

After y'all define a course that implements CommandLineArgumentProvider, y'all need to create an example and laissez passer it to the Android plugin using the annotationProcessorOptions.compilerArgumentProvider method, as shown below.

Not bad

// This is in your module's build.gradle file. android {     defaultConfig {         javaCompileOptions {             annotationProcessorOptions {                 // Creates a new MyArgsProvider object, specifies the input and                 // output paths for the constructor, and passes the object                 // to the Android plugin.                 compilerArgumentProvider new MyArgsProvider(files("input/path"),                                          new File("output/path"))             }         }     } }            

Kotlin

// This is in your module'southward build.gradle file. android {     defaultConfig {         javaCompileOptions {             annotationProcessorOptions {                 // Creates a new MyArgsProvider object, specifies the input and                 // output paths for the constructor, and passes the object                 // to the Android plugin.                 compilerArgumentProvider(MyArgsProvider(files("input/path"),                                                           file("output/path")))             }         }     } }            

To larn more about how implementing CommandLineArgumentProvider helps amend build functioning, read Caching Java projects.

Disable the notation processor fault check

If you lot accept dependencies on the compile classpath that include annotation processors yous don't need, y'all can disable the fault bank check by calculation the post-obit to your build.gradle file. Keep in listen, the annotation processors you add together to the compile classpath are still non added to the processor classpath.

Slap-up

android {     ...     defaultConfig {         ...         javaCompileOptions {             annotationProcessorOptions {                 includeCompileClasspath false             }         }     } }            

Kotlin

android {     ...     defaultConfig {         ...         javaCompileOptions {             annotationProcessorOptions {                 argument("includeCompileClasspath", "faux")             }         }     } }            

If you lot utilise Kotlin and kapt:

Groovy

android {     ...     defaultConfig {         ...         kapt {             includeCompileClasspath false         }     } }            

Kotlin

android {     ...     defaultConfig {         ...         kapt {             includeCompileClasspath = fake         }     } }            

If you experience issues after migrating your project'south notation processors to the processor classpath, you can let annotation processors on the compile classpath by setting includeCompileClasspath to true. Still, setting this property to truthful is non recommended, and the pick to practice then will be removed in a hereafter update of the Android plugin.

Exclude transitive dependencies

As an app grows in scope, information technology can contain a number of dependencies including direct dependencies and transitive dependencies (libraries which your app's imported libraries depend on). To exclude transitive dependencies that y'all no longer demand, yous tin can use the exclude keyword equally given below:

Peachy

dependencies {     implementation('some-library') {         exclude group: 'com.example.imgtools', module: 'native'     } }            

Kotlin

dependencies {     implementation("some-library") {         exclude(group = "com.example.imgtools", module = "native")     } }            

Exclude transitive dependencies from test configurations

If you demand to exclude certain transitive dependencies from your tests, the code sample shown higher up might not work equally expected. That's because a examination configuration (due east.k., androidTestImplementation) extends the module's implementation configuration. That is, it e'er contains implementation dependencies when Gradle resolves the configuration.

Then, to exclude transitive dependencies from your tests, you must practice and then at execution time as shown below:

Peachy

android.testVariants.all { variant ->     variant.getCompileConfiguration().exclude group: 'com.jakewharton.threetenabp', module: 'threetenabp'     variant.getRuntimeConfiguration().exclude group: 'com.jakewharton.threetenabp', module: 'threetenabp' }            

Kotlin

android.testVariants.all {     compileConfiguration.exclude(group = "com.jakewharton.threetenabp", module = "threetenabp")     runtimeConfiguration.exclude(group = "com.jakewharton.threetenabp", module = "threetenabp") }            

Annotation: You tin still utilize the exclude keyword in the dependencies block equally shown in the original lawmaking sample from the Exclude transitive dependencies section to omit transitive dependencies that are specific to the exam configuration and are not included in other configurations.

Configure Article of clothing OS app dependencies

Configuring dependencies for a Wearable Os module is similar to that of any other module; that is, Wear Bone modules utilise the same dependency configurations, such as implementation and compileOnly.

Clothing modules also support variant-aware dependency management. As a upshot, if your base app module has a dependency on a Habiliment module, each variant of the base module consumes the matching variant from the Wear module. If you are building a elementary app with a dependency on only one Wear module, where the module configures the same variants every bit your base module, y'all need to specify the wearApp configuration in your base of operations module'due south build.gradle file as shown below:

Groovy

                dependencies {     // If the main and Wear app modules have the same variants,     // variant-enlightened dependency management automatically matches     // variants of the main app module with that of the Wear module.     wearApp project(':wearable') }            

Kotlin

                dependencies {     // If the main and Wearable app modules have the same variants,     // variant-enlightened dependency management automatically matches     // variants of the master app module with that of the Wear module.     wearApp(project(":wearable")) }            

If you lot have multiple Wear modules and y'all want to specify a different Wear module per app flavor, you can practise and so using the flavorWearApp configuration, as follows (however, you can't include other dependencies that employ the wearApp configuration):

Neat

                dependencies {     paidWearApp projection(':wear1')     demoWearApp project(':wear1')     freeWearApp project(':wear2') }            

Kotlin

                dependencies {     "paidWearApp"(projection(":wear1"))     "demoWearApp"(projection(":wear1"))     "freeWearApp"(project(":wear2")) }            

Remote repositories

When your dependency is something other than a local library or file tree, Gradle looks for the files in whichever online repositories are specified in the dependencyResolutionManagement { repositories {...} } block of your settings.gradle file. The society in which you list each repository determines the gild in which Gradle searches the repositories for each projection dependency. For example, if a dependency is available from both repository A and B, and you list A first, Gradle downloads the dependency from repository A.

By default, new Android Studio projects specify Google's Maven repository, and the Maven central repository equally repository locations in the project's settings.gradle file, equally shown below:

Neat

                dependencyResolutionManagement {     repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)     repositories {         google()         mavenCentral()     } }            

Kotlin

                dependencyResolutionManagement {     repositoriesMode.set up(RepositoriesMode.FAIL_ON_PROJECT_REPOS)     repositories {         google()         mavenCentral()     } }            

If you desire something from a local repository use mavenLocal():

Groovy

                dependencyResolutionManagement {     repositoriesMode.fix(RepositoriesMode.FAIL_ON_PROJECT_REPOS)     repositories {         google()         mavenCentral()         mavenLocal()     } }            

Kotlin

                dependencyResolutionManagement {     repositoriesMode.ready(RepositoriesMode.FAIL_ON_PROJECT_REPOS)     repositories {         google()         mavenCentral()         mavenLocal()     } }            

Or you lot tin can declare specific Maven or Ivy repositories equally follows:

Groovy

                dependencyResolutionManagement {     repositoriesMode.gear up(RepositoriesMode.FAIL_ON_PROJECT_REPOS)     repositories {         maven {             url 'https://repo.case.com/maven2'         }         maven {             url 'file://local/repo/'         }         ivy {             url 'https://repo.instance.com/ivy'         }     } }            

Kotlin

                dependencyResolutionManagement {     repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)     repositories {         maven(url = "https://repo.case.com/maven2")         maven(url = "file://local/repo/")         ivy(url = "https://repo.example.com/ivy")     } }            

For more than information, see the Gradle Repositories guide.

Google's Maven repository

The most contempo versions of the following Android libraries are available from Google's Maven repository:

  • AndroidX Libraries
  • Compages Components Library
  • Constraint Layout Library
  • AndroidX Test
  • Databinding Library
  • Android Instant App Library
  • Wear Bone
  • Google Play services
  • Google Play Billing Library
  • Firebase

You can see all available artifacts at Google'southward Maven repository index (come across beneath for programmatic access).

To add i of these libraries to your build, include Google's Maven repository in your superlative-level build.gradle file:

Groovy

                dependencyResolutionManagement {      repositoriesMode.ready(RepositoriesMode.FAIL_ON_PROJECT_REPOS)     repositories {         google()          // If you lot're using a version of Gradle lower than iv.1, you must instead employ:         // maven {         //     url 'https://maven.google.com'         // }         // An alternative URL is 'https://dl.google.com/dl/android/maven2/'.     } }            

Kotlin

                dependencyResolutionManagement {      repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)     repositories {         google()          // If you're using a version of Gradle lower than iv.1, you must instead use:         // maven {         //     url = "https://maven.google.com"         // }         // An alternative URL is "https://dl.google.com/dl/android/maven2/".     } }            

Then add the desired library to your module's dependencies cake. For instance,the appcompat library looks like this:

Groovy

                dependencies {     implementation 'androidx.appcompat:appcompat:ane.2.0' }            

Kotlin

                dependencies {     implementation("com.android.back up:appcompat-v7:28.0.0") }            

However, if yous're trying to use an older version of the above libraries and your dependency fails, then it'south not bachelor in the Maven repository and y'all must instead get the library from the offline repository.

Programmatic access

For programmatic admission to Google'southward Maven artifacts, you can get an XML list of artifact groups from maven.google.com/chief-index.xml. Then, for whatsoever group, yous can view its library names and versions at:

maven.google.com/group_path/group-alphabetize.xml

For example, libraries in the android.arch.lifecycle group are listed at maven.google.com/android/arch/lifecycle/group-alphabetize.xml.

Yous can also download the POM and JAR files at:

maven.google.com/group_path/library/version /library-version.ext

For instance: maven.google.com/android/arch/lifecycle/compiler/ane.0.0/compiler-one. 0.0.pom.

Offline repository from SDK Director

For libraries non available from the Google Maven repository (usually older library versions), you lot must download the offline Google Repository package from the SDK Manager.

So you can add these libraries to your dependencies block as usual.

The offline libraries are saved in android_sdk/extras/.

Native dependencies with the Android Gradle plugin

AAR libraries can comprise native dependencies that the Android Gradle Plugin can consume. AGP is also capable of producing AARs that expose native libraries to their consumers.

Using native dependencies

Starting with Android Gradle plugin iv.0, C/C++ dependencies can exist imported from AARs linked in your build.gradle file. Gradle will automatically make these bachelor to the native build system, but your build system must exist configured to brand use of the imported libraries and headers. Since C/C++ dependencies are distributed as AARs, the post-obit links about generic AARs may be helpful:

  • Creating an Android Library for generic AAR documentation and how to integrate it into your project, especially when yous desire to utilize the AAR as a local C/C++ dependency.
  • Add build dependencies for information on adding dependencies to your build.gradle file, especially for the remote dependencies.

This document focuses on how to configure your native build organisation and assumes you've already added a C/C++ dependency AAR into your project'southward Gradle build environment.

Native dependencies in AARs

AAR dependencies of your Gradle modules tin expose native libraries for employ by your application. Inside the AAR, the prefab directory contains a Prefab package, which includes the headers and libraries of the native dependency.

Each dependency tin can expose at well-nigh one Prefab parcel, which comprises 1 or more than modules. A Prefab module is a single library, which could exist either a shared, static, or header but library.

The package and module names need to exist known to brand use of the libraries. Past convention the package name will match the Maven artifact name and the module name will match the C/C++ library proper noun, but this is non required. Consult the dependency's documentation to decide what names it uses.

Build organisation configuration

The prefab feature must be enabled for your Android Gradle module.

To do so, add together the following to the android block of your module's build.gradle file:

Groovy

buildFeatures {   prefab true }            

Kotlin

buildFeatures {   prefab = true }            

Optionally, configure a version in your project'south gradle.properties file:

          android.prefabVersion=2.0.0                  

Typically the default version selected AGP will fit your needs. You should only need to select a different version if there is a issues y'all need to work around or a new feature yous desire.

Dependencies imported from an AAR are exposed to CMake via CMAKE_FIND_ROOT_PATH. This value will exist set automatically by Gradle when CMake is invoked, and so if your build modifies this variable exist sure to suspend rather than assign to it.

Each dependency exposes a config-file package to your build. These are imported with the find_package command. This control searches for config-file packages matching the given package name and version and exposes the targets it defines to exist used in your build. For example, if your application defines libapp.and then and it uses cURL, your CMakeLists.txt should include the following:

          add_library(app SHARED app.cpp)  # Add these ii lines. find_package(curl REQUIRED CONFIG) target_link_libraries(app curl::curl)                  

app.cpp is now able to #include "curlicue/curl.h", libapp.so will be automatically linked against libcurl.and then when building, and libcurl.so will be included with the app.

Publishing native libraries in AARs

The power to create native AARs was get-go added in AGP four.1.

To export your native libraries, add the post-obit to the android block of your library project'south build.gradle file:

Keen

                buildFeatures {     prefabPublishing true }  prefab {              mylibrary              {       headers "src/chief/cpp/mylibrary/include"     }              myotherlibrary              {         headers "src/primary/cpp/myotherlibrary/include"     } }            

Kotlin

                buildFeatures {     prefabPublishing = true }  prefab {     create("mylibrary") {       headers = "src/principal/cpp/mylibrary/include"     }      create("myotherlibrary") {         headers = "src/main/cpp/myotherlibrary/include"     } }            

In this example, the mylibrary and myotherlibrary libraries from either your ndk-build or CMake external native build will be packaged in the AAR produced by your build, and each volition export the headers from the specified directory to their dependents.

Dependency social club

The order in which y'all list your dependencies indicates the priority for each: the first library is higher priority than the second, the 2d is higher priority than the tertiary, and and then on. This order is important in the event that resources are merged or manifest elements are merged into your app from the libraries.

For example, if your project declares the following:

  • Dependency on LIB_A and LIB_B (in that society)
  • And LIB_A depends on LIB_C and LIB_D (in that order)
  • And LIB_B besides depends on LIB_C

Then, the flat dependency club volition be as follows:

  1. LIB_A
  2. LIB_D
  3. LIB_B
  4. LIB_C

This ensures that both LIB_A and LIB_B can override LIB_C; and LIB_D is withal higher priority than LIB_B because LIB_A (which depends on it) has college priority than LIB_B.

For more information nearly how manifests from different project sources/dependencies are merged, see Merge multiple manifest files.

View module dependencies

Some direct dependencies may take dependencies of their ain. These are called transitive dependencies. Rather than requiring yous to manually declare each transitive dependency, Gradle automatically gathers and adds them for yous. The Android plugin for Gradle provides a task that displays a list of the dependencies Gradle resolves for a given module.

For each module, the report besides groups the dependencies based on build variant, testing source prepare, and classpath. The following is sample report for an app module'south runtime classpath of its debug build variant and compile classpath of its instrumented test source gear up.

          debugRuntimeClasspath - Dependencies for runtime/packaging +--- :mylibrary (variant: debug) +--- com.google.android.material:cloth:1.0.0@aar +--- androidx.appcompat:appcompat:ane.0.2@aar +--- androidx.constraintlayout:constraintlayout:1.one.three@aar +--- androidx.fragment:fragment:1.0.0@aar +--- androidx.vectordrawable:vectordrawable-animated:one.0.0@aar +--- androidx.recyclerview:recyclerview:1.0.0@aar +--- androidx.legacy:legacy-support-core-ui:1.0.0@aar ...  debugAndroidTest debugAndroidTestCompileClasspath - Dependencies for compilation +--- androidx.test.ext:junit:one.1.0@aar +--- androidx.test.espresso:espresso-cadre:iii.1.1@aar +--- androidx.examination:runner:1.ane.ane@aar +--- junit:junit:4.12@jar ...                  

To run the job, proceed as follows:

  1. Select View > Tool Windows > Gradle (or click Gradle in the tool windows bar).
  2. Aggrandize AppName > Tasks > android and double-click androidDependencies. After Gradle executes the task, the Run window should open up to display the output.

For more information about managing dependencies in Gradle, come across Dependency management basics in the Gradle User Guide.

Fix dependency resolution errors

When you add multiple dependencies to your app project, those direct and transitive dependencies might disharmonize with one another. The Android Gradle plugin tries to resolve these conflicts gracefully, simply some conflicts may lead to compile time or runtime errors.

To assist y'all investigate which dependencies are contributing to errors, inspect your app's dependency tree and look for dependencies that announced more than than once or with conflicting versions.

If you tin can't easily identify the indistinguishable dependency, endeavor using Android Studio'south UI to search for dependencies that include the duplicate class as follows:

  1. Select Navigate > Class from the menu bar.
  2. In the pop-upwardly search dialog, brand sure that the box side by side to Include non-project items is checked.
  3. Blazon the proper noun of the class that appears in the build error.
  4. Inspect the results for the dependencies that include the class.

The following sections depict the different types of dependency resolution errors you may encounter and how to fix them.

Fix duplicate class errors

If a class appears more than once on the runtime classpath, yous get an error similar to the post-obit:

Program type already present com.example.MyClass        

This fault typically occurs due to ane of the following circumstances:

  • A binary dependency includes a library that your app also includes as a directly dependency. For example, your app declares a direct dependency on Library A and Library B, only Library A already includes Library B in its binary.
    • To resolve this consequence, remove Library B as a directly dependency.
  • Your app has a local binary dependency and a remote binary dependency on the same library.
    • To resolve this issue, remove 1 of the binary dependencies.

Fix conflicts between classpaths

When Gradle resolves the compile classpath, information technology first resolves the runtime classpath and uses the result to determine what versions of dependencies should exist added to the compile classpath. In other words, the runtime classpath determines the required version numbers for identical dependencies on downstream classpaths.

Your app's runtime classpath also determines the version numbers that Gradle requires for matching dependencies in the runtime classpath for the app'south test APK. The hierarchy of classpaths is described in effigy i.

Effigy 1. Version numbers of dependencies that appear across multiple classpaths must lucifer according to this hierarchy.

A disharmonize where different versions of the same dependency appears across multiple classpaths might occur when, for example, your app includes a version of a dependency using the implementation dependency configuration and a library module includes a unlike version of the dependency using the runtimeOnly configuration.

When resolving dependencies on your runtime and compile fourth dimension classpaths, Android Gradle plugin three.3.0 and higher attempt to automatically fix certain downstream version conflicts. For example, if the runtime classpath includes Library A version ii.0 and the compile classpath includes Library A version 1.0, the plugin automatically updates the dependency on the compile classpath to Library A version 2.0 to avert errors.

However, if the runtime classpath includes Library A version ane.0 and the compile classpath includes Library A version 2.0, the plugin does not downgrade the dependency on the compile classpath to Library A version ane.0, and you nonetheless get an error like to the following:

Conflict with dependency 'com.example.library:some-lib:two.0' in project 'my-library'. Resolved versions for runtime classpath (1.0) and compile classpath (2.0) differ.        

To resolve this issue, practise i of the following:

  • Include the desired version of the dependency as an api dependency to your library module. That is, simply your library module declares the dependency, but the app module will besides accept access to its API, transitively.
  • Alternatively, you can declare the dependency in both modules, but yous should make sure that each module uses the aforementioned version of the dependency. Consider configuring projection-broad properties to ensure versions of each dependency remain consistent throughout your project.

Utilise custom build logic

This section describes avant-garde topics that are useful when you want to extend the Android Gradle plugin or write your own plugin.

Publish variant dependencies to custom logic

A library can have functionalities that other projects or sub-projects might want to use. Publishing a library is the process by which the library is made available to its consumers. Libraries can control which dependencies its consumers take admission to at compile time and runtime.

There are ii separate configurations that hold the transitive dependencies of each classpath which must be used past consumers to consume the library as described below:

  • variant_nameApiElements: This configuration holds the transitive dependencies that are available to consumers at compile fourth dimension.
  • variant_nameRuntimeElements: This configuration holds the transitive dependencies that are available to consumers at runtime.

To acquire more than well-nigh the relationships between the different configurations, get to The Java Library plugin configurations.

Custom dependency resolution strategies

A project may include a dependency on two different versions of the same library which can lead to dependency conflicts. For instance, if your project depends on version 1 of module A and version 2 of module B, and module A transitively depends on version 3 of module B, at that place arises a dependency version disharmonize.

To resolve this conflict, the Android Gradle plugin uses the following dependency resolution strategy: when the plugin detects that unlike versions of the same module are in the dependency graph, by default, it chooses the one with the highest version number.

However, this strategy might not ever work equally you intend. To customize the dependency resolution strategy, utilize the post-obit configurations to resolve specific dependencies of a variant that are needed for your task:

  • variant_nameCompileClasspath: This configuration contains the resolution strategy for a given variant's compile classpath.
  • variant_nameRuntimeClasspath: This configuration contains the resolution strategy for a given variant'south runtime classpath.

The Android Gradle plugin includes getters that you tin can use to access the configuration objects of each variant. Thus, y'all tin can apply the variant API to query the dependency resolution as shown in the example below:

Groovy

android {     applicationVariants.all { variant ->         // Return compile configuration objects of a variant.         variant.getCompileConfiguration().resolutionStrategy {         // Use Gradle'due south ResolutionStrategy API         // to customize how this variant resolves dependencies.             ...         }         // Return runtime configuration objects of a variant.         variant.getRuntimeConfiguration().resolutionStrategy {             ...         }         // Return annotation processor configuration of a variant.         variant.getAnnotationProcessorConfiguration().resolutionStrategy {             ...         }     } }

Kotlin

android {     applicationVariants.all {         // Return compile configuration objects of a variant.         compileConfiguration.resolutionStrategy {         // Use Gradle'due south ResolutionStrategy API         // to customize how this variant resolves dependencies.             ...         }         // Return runtime configuration objects of a variant.         runtimeConfiguration.resolutionStrategy {             ...         }         // Render note processor configuration of a variant.         annotationProcessorConfiguration.resolutionStrategy {             ...         }     } }

Dependency information for Play Panel

When building your app using AGP 4.0.0 and college, the plugin includes metadata that describes the library dependencies that are compiled into your app. When uploading your app, the Play Console inspects this metadata to provide alerts for known issues with SDKs and dependencies your app uses, and, in some cases, provide actionable feedback to resolve those issues.

The data is compressed, encrypted past a Google Play signing key, and stored in the signing block of your release app. Nosotros recommend keeping this dependencies file for a safe and positive user experience. All the same, if you'd rather not share this information, you can opt out by including the following dependenciesInfo block in your module's build.gradle file:

          android {     dependenciesInfo {         // Disables dependency metadata when building APKs.         includeInApk = false         // Disables dependency metadata when building Android App Bundles.         includeInBundle = false     } }                  

For more information on our policies and potential problems with dependencies, see our support page on using third-party SDKs in your app.

How To Add Maven Dependency In Android Studio,

Source: https://developer.android.com/studio/build/dependencies

Posted by: mosstheirach.blogspot.com

0 Response to "How To Add Maven Dependency In Android Studio"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel