构建-4 dependencies 依赖管理


Add build dependencies

The Gradle build system in Android Studio makes it easy to include external binaries外部二进制文件 or other library modules to your build as dependencies. The dependencies can be located on your machine or in a remote repository, and any transitive dependencies they declare所声明的传递依赖 are automatically included as well. This page describes how to use 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 also see the Gradle guide for dependency management—but remember that your Android project must use only the dependency configurations defined on this page.

Dependency types

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

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

apply plugin: 'com.android.application'

android { ... }
dependencies {
    implementation project(":mylibrary") // Dependency on a local library module
    implementation fileTree(dir: 'libs', include: ['*.jar']) // Dependency on local binaries
    implementation 'com.example.android:app-magic:12.3' // Dependency on a remote binary
}
8
8
 
1
apply plugin: 'com.android.application'
2
3
android { ... }
4
dependencies {
5
    implementation project(":mylibrary") // Dependency on a local library module
6
    implementation fileTree(dir: 'libs', include: ['*.jar']) // Dependency on local binaries
7
    implementation 'com.example.android:app-magic:12.3' // Dependency on a remote binary
8
}

Each of these request a different kind of dependency as follows:

Local library module dependency
implementation project(':mylibrary') //implementation project(path: ':mylibrary')
 
1
implementation project(':mylibrary') //implementation project(path: ':mylibrary')

This declares a dependency on an Android library module named "mylibrary" (this name must match the library name defined as an include in your settings.gradle file). When you build your app, the build system compiles the library module and packages the resulting AAR file in the APK.

Local binary dependency
implementation fileTree(dir: 'libs', include: ['*.jar'])  //fileTree
1
1
1
implementation fileTree(dir: 'libs', include: ['*.jar'])  //fileTree

Because Gradle reads paths relative to the build.gradle file, this tells the build system to add all JAR files inside your project's module_name/libs/ directory as dependencies.

Alternatively或者、作为选择、非此即彼, you specify individual个别的 files as follows:

implementation files('libs/foo.jar', 'libs/bar.jar') //files
 
1
implementation files('libs/foo.jar', 'libs/bar.jar') //files
Remote binary dependency
implementation 'com.example.android:app-magic:12.3'
1
1
1
implementation 'com.example.android:app-magic:12.3'

This is actually事实上 shorthand速记 for the following:

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

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

Note: Remote dependencies like 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 as when you click Sync Project with Gradle Files  or when you run a build).

Library dependency configurations

Inside the dependencies block, you can declare a library dependency using one of several different dependency configurations (such as implementation shown above). Each dependency configuration provides Gradle different instructions指令 about how to use the library. The following table describes each of the configurations you can use for a library dependency in your Android project. The table also compares these configurations to those that were deprecated as of Android Gradle Plugin 3.0.0.

implementation[compile]

Gradle adds the dependency to the compilation classpath and packages打包到 the dependency to the build output. However, when your module configures an implementation dependency, it's letting Gradle know that you do not want the module to leak泄露给 the dependency to other modules at compile time. That is, the dependency is available to other modules only at runtime.

Using this dependency configuration instead of api or compile (deprecated) can result insignificant build time improvements because it reduces减少了 the number of modules that the build system needs to recompile.For example, if an implementation dependency changes its API, Gradle recompiles only that dependency and the modules that directly直接 depend on it. Most app and test modules should use this configuration.

result insignificant build time improvements 导致构建时间有微小的提升
这句话里面的 insignificant 原本意思是"无关紧要的、不必要的、无足轻重的"意思,感觉像是否定意思一样,但实际是肯定是意思。
这句话里面的 improvements 的意思并不是"提高"了构建时间,而是"提升"了构建事件,意思也就是"降低"了构建时间。
MLGB的,这句话让我产生了巨大的误解!
1
result insignificant build time improvements 导致构建时间有微小的提升
2
这句话里面的 insignificant 原本意思是"无关紧要的、不必要的、无足轻重的"意思,感觉像是否定意思一样,但实际是肯定是意思。
3
这句话里面的 improvements 的意思并不是"提高"了构建时间,而是"提升"了构建事件,意思也就是"降低"了构建时间。
4
MLGB的,这句话让我产生了巨大的误解!

api[compile]

Gradle adds the dependency to the compilation classpath and build output.When a module includes an api dependency, it's letting Gradle know that the module wants to transitively传递的 export传递、输出 that dependency to other modules, so that it's available to them at both runtime and compile time. This configuration behaves just like compile (which is now deprecated), but you should use it with caution谨慎、小心. You should typically通常的、典型的、代表性的 use api dependencies only in library modules. That's because, if an api dependency changes its external外部 API, Gradle recompiles all modules that have access to有权访问 that dependency at compile time. So, having a large number of api dependencies can significantly显著的 increase build times. Unless you want to expose公开给 a dependency's API to a separate单独的、分开的 test module, app modules should instead use implementation dependencies.

compileOnly[provided]

Gradle adds the dependency to the compilation classpath only (that is, it is not added to the build output).
This is useful when you're creating an Android library module and you need the dependency during compilation, but it's optional to have present可以使用 at runtime. That is, if you use this configuration, then your library module must include a runtime condition条件、情况 to check whether the dependency is available, and then gracefully优雅地 change its behavior so it can still function执行功能 if it's not provided. This helps reduce the size of the final APK by not adding transient瞬态、短时的 dependencies that aren't critical决定性的、不重要的. This configuration behaves just like provided (which is now deprecated).

runtimeOnly[apk]

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


The above configurations apply to your project's main source set, which is applied 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, you must capitalize利用 the configuration name and prefix前缀 it with the name of the build variant or testing source set.

For example, to add an implementation dependency only to your "free" product flavor , it looks like this:

dependencies {
    freeImplementation 'com.google.firebase:firebase-ads:9.8.0' // Implementation 的基础上加 build variant 的前缀
}
3
3
 
1
dependencies {
2
    freeImplementation 'com.google.firebase:firebase-ads:9.8.0' // Implementation 的基础上加 build variant 的前缀
3
}

However, if you want to add a dependency for a variant that combines a product flavor and a build type, then you must initialize the configuration name in the configurations block. The following sample adds a runtimeOnlydependency to your "freeDebug" build variant:

configurations {
    // Initializes a placeholder for the freeDebugRuntimeOnly dependency configuration.
    freeDebugRuntimeOnly {} // runtimeOnly的基础上加 free(product flavor) 和 Debug(build type) 的前缀
}
dependencies {
    freeDebugRuntimeOnly fileTree(dir: 'libs', include: ['*.jar'])
}
 
1
configurations {
2
    // Initializes a placeholder for the freeDebugRuntimeOnly dependency configuration.
3
    freeDebugRuntimeOnly {} // runtimeOnly的基础上加 free(product flavor) 和 Debug(build type) 的前缀
4
}
5
dependencies {
6
    freeDebugRuntimeOnly fileTree(dir: 'libs', include: ['*.jar'])
7
}

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

dependencies {
    testImplementation 'junit:junit:4.12' // Adds a remote binary dependency only for local tests.
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' // only for the instrumented test APK.
}
4
4
 
1
dependencies {
2
    testImplementation 'junit:junit:4.12' // Adds a remote binary dependency only for local tests.
3
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' // only for the instrumented test APK.
4
}

However, certain configurations don't make sense in this situation. For example, because other modules can't depend on androidTest, you get the following warning if you use the androidTestApi configuration:

WARNING: Configuration 'androidTestApi' is obsolete废弃 and has been replaced with 'androidTestImplementation'
1
1
1
WARNING: Configuration 'androidTestApi' is obsolete废弃 and has been replaced with 'androidTestImplementation'

Android plugin for Gradle 3.0.0 and higher automatically自动 match each variant of your app with corresponding variants of its local library module dependencies其本地库模块依赖项的相应变体 for you. That is, you should no longer target针对 specific variants of local module dependencies本地模块依赖项的特定变体. To learn more, read Use variant-aware dependency management.

For more information on dependency management, see Java Plugin dependency management.

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 repositories block of your build.gradle file.

By default, new Android Studio projects declare JCenter as the repository location in the project's top-level build.gradle file, as shown here:

allprojects {
    repositories {
        jcenter()
    }
}
1
allprojects {
2
    repositories {
3
        jcenter()
4
    }
5
}

If you want something from the Maven central repository, then add mavenCentral(), or for a local repository use mavenLocal():

allprojects {
    repositories {
        jcenter()
        mavenCentral()
        mavenLocal()
    }
}
7
7
1
allprojects {
2
    repositories {
3
        jcenter()
4
        mavenCentral()
5
        mavenLocal()
6
    }
7
}

Or you can declare specific Maven or Ivy常春藤联盟的 repositories as follows:

allprojects {
    repositories {
        maven {
            url "https://repo.example.com/maven2"
        }
        maven {
            url "file://local/repo/"
        }
        ivy {
            url "https://repo.example.com/ivy"
        }
    }
}
13
13
 
1
allprojects {
2
    repositories {
3
        maven {
4
            url "https://repo.example.com/maven2"
5
        }
6
        maven {
7
            url "file://local/repo/"
8
        }
9
        ivy {
10
            url "https://repo.example.com/ivy"
11
        }
12
    }
13
}

For more information, see the Gradle Repositories guide.

Google's Maven repository

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

You can see all available artifacts上古神器 at Google's Maven repository index (see below for programmatic access).

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

allprojects {
    repositories {
        google() // If you're using a version of Gradle lower than 4.1, you must instead use:【maven { url 'https://maven.google.com'}】
    }
}
 
1
allprojects {
2
    repositories {
3
        google() // If you're using a version of Gradle lower than 4.1, you must instead use:【maven { url 'https://maven.google.com'}】
4
    }
5
}

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

dependencies {
    implementation 'com.android.support:appcompat-v7:27.1.1'
}
3
3
 
1
dependencies {
2
    implementation 'com.android.support:appcompat-v7:27.1.1'
3
}

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


Programmatic access 编程方式访问

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

【maven.google.com/group_path/group-index.xml】

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

You can also download the POM and JAR files at:

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

For example: maven.google.com/android/arch/lifecycle/compiler/1.0.0/compiler-1. 0.0.pom.


Offline repository from SDK Manager

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

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

The offline libraries are saved in android_sdk/extras/.

Dependency order

The order in which you list your dependencies indicates the priority for each: the first library is higher priority than the second, the second is higher priority than the third, and so 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 order)
  • And LIB_A depends on LIB_C and LIB_D (in that order)
  • And LIB_B also depends on LIB_C

Then, the flat dependency order will be as follows:

  • LIB_A
  • LIB_D
  • LIB_B
  • LIB_C

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

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

View the dependency tree

Some direct直接 dependencies may have dependencies of their own. These are called transitive传递 dependencies. Rather than requiring you to manually declare不会要求您手动声明 each transitive dependency, Gradle automatically gathers收集 and adds them for you. To visualize可视化项目 both the direct and transitive dependencies of your project, the Android plugin for Gradle provides a Gradle task that generates a dependency tree依赖树 for each build variant and testing source set.

To run the task, proceed as follows:

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

The following sample output shows the dependency tree for the debug build variant, and includes the local library module dependency and remote dependency from the previous example.

Executing tasks: [androidDependencies]
:app:androidDependencies
debug
// Both the library module dependency and remote binary dependency are listed with their transitive dependencies.
+--- MyApp:mylibrary:unspecified
|    \--- com.android.support:appcompat-v7:27.1.1
|         +--- com.android.support:animated-vector-drawable:27.1.1
|         |    \--- com.android.support:support-vector-drawable:27.1.1
|         |         \--- com.android.support:support-v4:27.1.1
|         |              \--- LOCAL: internal_impl-27.1.1.jar
|         +--- com.android.support:support-v4:27.1.1
|         |    \--- LOCAL: internal_impl-27.1.1.jar
|         \--- com.android.support:support-vector-drawable:27.1.1
|              \--- com.android.support:support-v4:27.1.1
|                   \--- LOCAL: internal_impl-27.1.1.jar
\--- com.android.support:appcompat-v7:27.1.1
     +--- com.android.support:animated-vector-drawable:27.1.1
     |    \--- com.android.support:support-vector-drawable:27.1.1
     |         \--- com.android.support:support-v4:27.1.1
     |              \--- LOCAL: internal_impl-27.1.1.jar
     +--- com.android.support:support-v4:27.1.1
     |    \--- LOCAL: internal_impl-27.1.1.jar
     \--- com.android.support:support-vector-drawable:27.1.1
          \--- com.android.support:support-v4:27.1.1
               \--- LOCAL: internal_impl-27.1.1.jar
...
x
1
Executing tasks: [androidDependencies]
2
:app:androidDependencies
3
debug
4
// Both the library module dependency and remote binary dependency are listed with their transitive dependencies.
5
+--- MyApp:mylibrary:unspecified
6
|    \--- com.android.support:appcompat-v7:27.1.1
7
|         +--- com.android.support:animated-vector-drawable:27.1.1
8
|         |    \--- com.android.support:support-vector-drawable:27.1.1
9
|         |         \--- com.android.support:support-v4:27.1.1
10
|         |              \--- LOCAL: internal_impl-27.1.1.jar
11
|         +--- com.android.support:support-v4:27.1.1
12
|         |    \--- LOCAL: internal_impl-27.1.1.jar
13
|         \--- com.android.support:support-vector-drawable:27.1.1
14
|              \--- com.android.support:support-v4:27.1.1
15
|                   \--- LOCAL: internal_impl-27.1.1.jar
16
\--- com.android.support:appcompat-v7:27.1.1
17
     +--- com.android.support:animated-vector-drawable:27.1.1
18
     |    \--- com.android.support:support-vector-drawable:27.1.1
19
     |         \--- com.android.support:support-v4:27.1.1
20
     |              \--- LOCAL: internal_impl-27.1.1.jar
21
     +--- com.android.support:support-v4:27.1.1
22
     |    \--- LOCAL: internal_impl-27.1.1.jar
23
     \--- com.android.support:support-vector-drawable:27.1.1
24
          \--- com.android.support:support-v4:27.1.1
25
               \--- LOCAL: internal_impl-27.1.1.jar
26
...

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

Resolve duplicate class errors

When you add multiple dependencies to your app project, there's a possibility that those direct and transitive dependencies might conflict冲突 with one another, and lead to导致 compile time or runtime errors.

For example, you get the following error if a class appears more than once on the runtime classpath:

Program type already present出现 com.example.MyClass
 
1
Program type already present出现 com.example.MyClass

This error typically通常 occurs发生 due to由于 one of the following circumstances情况、环境:

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

You may also see the following error if different versions of the same transitive dependency appear in the compile time and runtime classpaths:

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

This can occur when, for example, your app includes a version of a dependency using theimplementationdependency configurationand a library module includes a different version of the dependency using the runtimeOnlyconfiguration. To resolve this issue, do one of the following:

  • Include the desired期望的 version of the dependency as an api dependency to your library module. That is, only your library module declares the dependency, but the app module will also have access to its API, transitively.
  • Alternatively作为选择, you can declare the dependency in both modules, but you should make sure that each module uses the same version of the dependency. Consider configuring project-wide properties to ensure versions of each dependency remain保持 consistent一致 throughout贯穿 your project.

To help you investigate探究 which dependencies are contributing to errors, inspect your app's dependency tree and look for dependencies that appear more than once or with conflicting versions.

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

  1. Select Navigate > Class from the menu bar.
  2. In the pop-up search dialog, make sure that the box next to Include non-project items is checked.
  3. Type the class that appeared in the build error.
  4. Inspect the results for the dependencies that include the class.

implementation、api、compile的区别

api 完全等同于 compile,两者没区别,你将所有的 compile 改成 api时完全没有错。

implementation  这个指令的特点就是,对于使用了该命令编译的依赖,对该项目有依赖的项目将无法访问到使用该命令编译的依赖中的任何程序,也就是将该依赖隐藏在内部,而不对外部公开。
简单的说就是,使用 implementation 指令的依赖只作用于当前的 module,而不会传递。

例如,有一个 module testsdk 依赖于 gson:
implementation 'com.google.code.gson:gson:2.8.2' //testsdk 通过 implementation 依赖于 gson
x
1
implementation 'com.google.code.gson:gson:2.8.2' //testsdk 通过 implementation 依赖于 gson
另一个 module app 依赖于 testsdk:
implementation project(':testsdk') //app 依赖于 testsdk
1
implementation project(':testsdk') //app 依赖于 testsdk
这时候,因为testsdk使用的是 implementation 指令来依赖 gson,所以 app 里边不能引用 gson。

但是,如果 testsdk 使用的是 api 来引用 gson:
api 'com.google.code.gson:gson:2.8.2' //testsdk 通过 api 依赖于 gson
x
 
1
api 'com.google.code.gson:gson:2.8.2' //testsdk 通过 api 依赖于 gson
则与 Gradle3.0.0 之前的 compile 指令的效果完全一样,app 的 module 也可以引用 gson。

迁移指南
理论上,你可以将原来工程中的 compile 完全替换为现在的 api,但是一旦依赖发生变化,将会使所有的 module 重新编译,造成编译过长。
所以更好的方式就是使用 implementation 来进行依赖,这会改善工程的构建时间。只有你明确要向外部暴露所依赖 lib 的接口时,才需要使用 api 依赖,整体来说,会减少很多重新编译。这一点,在 官方指南中说的比较明确。

2018-7-24

猜你喜欢

转载自www.cnblogs.com/baiqiantao/p/9361673.html