应用自定义构建逻辑

本部分介绍的高级主题在您要扩展 Android Gradle 插件或编写自己的插件时很有用。

向自定义逻辑发布变体依赖项

库可以包含其他项目或子项目可能要使用的功能。发布库是向其消费者提供库的过程。库可以控制其消费者在编译时和运行时可访问的依赖项。

有两种不同的配置,它们包含每个类路径的传递依赖项,消费者为了使用相应库而必须使用这些依赖项,具体说明如下:

  • variant_nameApiElements:此配置包含编译时消费者可使用的传递依赖项。
  • variant_nameRuntimeElements:此配置包含消费者在运行时可使用的传递依赖项。

如需详细了解不同配置之间的关系,请参阅 Java 库插件配置

自定义依赖项解析策略

一个项目可能会依赖于同一个库的两个不同版本,这样会导致依赖项冲突。例如,如果您的项目依赖于模块 A 的版本 1 和模块 B 的版本 2,而模块 A 以传递方式依赖于模块 B 的版本 3,则会出现依赖项版本冲突。

为了解决此冲突,Android Gradle 插件使用以下依赖项解析策略:当插件检测到依赖项关系图中存在同一模块的不同版本时,默认情况下,它会选择版本号最高的一个。

不过,此策略可能并不总是如您所愿。如需自定义依赖项解析策略,请使用以下配置解析任务所需的特定变体依赖项:

  • variant_nameCompileClasspath:此配置包含适用于给定变体编译类路径的解析策略。
  • variant_nameRuntimeClasspath:此配置包含适用于给定变体运行时类路径的解析策略。

Android Gradle 插件包含可用于访问每个变体的配置对象的 getter。因此,您可以使用变体 API 查询依赖项解析,如以下示例所示:

KotlinGroovy
android {
    applicationVariants
.all {
       
// Return compile configuration objects of a variant.
        compileConfiguration
.resolutionStrategy {
       
// Use Gradle's ResolutionStrategy API
       
// to customize how this variant resolves dependencies.
           
...
       
}
       
// Return runtime configuration objects of a variant.
        runtimeConfiguration
.resolutionStrategy {
           
...
       
}
       
// Return annotation processor configuration of a variant.
        annotationProcessorConfiguration
.resolutionStrategy {
           
...
       
}
   
}
}
android {
    applicationVariants
.all { variant ->
       
// Return compile configuration objects of a variant.
        variant
.getCompileConfiguration().resolutionStrategy {
       
// Use Gradle's 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 {
           
...
       
}
   
}
}