用途
该技能帮助开发者为 Android 应用配置可扩展、易维护的构建系统,使用 Gradle Convention Plugins(约定插件)和 Version Catalogs(版本目录),并遵循 "Now in Android"(NiA)架构。其核心目标是:停止在多个 build.gradle.kts 文件之间复制粘贴代码,将构建逻辑(Compose 配置、Kotlin 选项、Hilt 等)集中到可复用的插件中。
主要能力
- 指导建立 build-logic 目录,并在 settings.gradle.kts 中作为复合构建(composite build)引入。
- 使用 Version Catalog(libs.versions.toml)统一管理库和插件的版本。
- 编写自定义 Convention Plugin(如 AndroidApplicationConventionPlugin),集中配置 Android 应用/库的通用选项。
- 在 build-logic/convention/build.gradle.kts 中通过 gradlePlugin 块注册插件。
- 在模块级 build.gradle.kts 中通过 alias 应用自定义插件,从而大幅精简模块构建文件。
使用方式
项目结构
确保项目包含 build-logic 目录,并在 settings.gradle.kts 中作为复合构建引入:
root/
├── build-logic/
│ ├── convention/
│ │ ├── src/main/kotlin/
│ │ │ └── AndroidApplicationConventionPlugin.kt
│ │ └── build.gradle.kts
│ ├── build.gradle.kts
│ └── settings.gradle.kts
├── gradle/
│ └── libs.versions.toml
├── app/
│ └── build.gradle.kts
└── settings.gradle.kts
第 1 步:配置 settings.gradle.kts
将 build-logic 作为插件管理源引入:
// settings.gradle.kts
pluginManagement {
includeBuild("build-logic")
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
第 2 步:在 libs.versions.toml 中定义依赖
为库和插件使用 Version Catalog:
[versions]
androidGradlePlugin = "8.2.0"
kotlin = "1.9.20"
[libraries]
# ...
[plugins]
android-application = { id = "com.android.application", version.ref = "androidGradlePlugin" }
android-library = { id = "com.android.library", version.ref = "androidGradlePlugin" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
# Define your own plugins here
nowinandroid-android-application = { id = "nowinandroid.android.application", version = "unspecified" }
第 3 步:创建约定插件
在 build-logic/convention/src/main/kotlin/AndroidApplicationConventionPlugin.kt 中:
import com.android.build.api.dsl.ApplicationExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure
class AndroidApplicationConventionPlugin : Plugin<Project> {
override fun apply(target: Project) {
with(target) {
with(pluginManager) {
apply("com.android.application")
apply("org.jetbrains.kotlin.android")
}
extensions.configure<ApplicationExtension> {
defaultConfig.targetSdk = 34
// Configure common options here
}
}
}
}
别忘了在 build-logic/convention/build.gradle.kts 中注册它:
gradlePlugin {
plugins {
register("androidApplication") {
id = "nowinandroid.android.application"
implementationClass = "AndroidApplicationConventionPlugin"
}
}
}
使用
在模块(例如 app/build.gradle.kts)中应用自定义插件:
plugins {
alias(libs.plugins.nowinandroid.android.application)
}
这会大幅精简模块级构建文件。
适用场景
- 拥有多个模块的 Android 项目,需要统一构建配置。
- 希望减少 build.gradle.kts 中的重复代码。
- 采用 "Now in Android" 架构或类似约定插件模式的项目。
- 需要集中管理 Compose、Kotlin、Hilt 等通用构建选项。
限制
资料中未提供关于该技能的具体限制、兼容的 Gradle/AGP 版本范围、收费或价格信息,以及除上述示例外的其他使用步骤。