项目骨架与 Gradle 构建工具链
一句话:现代 Android 工程的可复制性,全部押在 Version Catalog (
libs.versions.toml) 这一个文件上。版本对齐对了,后面 20 篇编译不出问题;对错了,从第 03 篇开始就掉进版本号地狱。
一、为什么要专门讲"构建"
写 Web 的人很少专门学打包工具(vite.config.ts 抄一份就能跑);写后端的人很少专门学 Maven(pom.xml 模板抄一份就能跑)。Android 不一样——Android 的构建系统本身就是工程的一部分。
原因有三个:
- 三方 SDK 全靠 Gradle 集成——Compose / Hilt / Room / Retrofit / kotlinx.serialization 每个都需要正确配置插件、依赖、KSP 注解处理器,缺一不可。
- 版本对齐极其敏感——AGP × Kotlin × Compose Compiler × KSP 四件事必须互相匹配,错一个就连 Hello World 都编不过。
- 构建产物决定一切——你最终交给 Play Console 的是 AAB,不是源码;AAB 的签名、混淆、瘦身、签名都在 Gradle 里配置。
所以这一篇不能跳。把 libs.versions.toml 抄对了,后面 20 篇都是顺水推舟。
二、四份关键文件
一个现代 Android 工程的 Gradle 配置由四份文件构成:
项目根/
├── settings.gradle.kts ← 项目层面:模块列表、插件仓库、依赖仓库
├── build.gradle.kts ← 根 build,只用来声明插件版本(不应用)
├── gradle/
│ └── libs.versions.toml ← Version Catalog:所有版本号 / 库 / 插件
└── app/
└── build.gradle.kts ← 模块层面:具体应用插件、依赖、Android 配置关键约束:版本号只写在 libs.versions.toml。build.gradle.kts 里不准出现裸版本字符串。这样你升级 Compose 时只改一个文件,不用全项目搜替换。
三、libs.versions.toml 钉死版本
下面是 NotedX 的 Version Catalog,直接抄,后面 20 篇都基于这份:
[versions]
agp = "8.7.2"
kotlin = "2.0.21"
ksp = "2.0.21-1.0.27" # 与 Kotlin 强绑定,见下表
hilt = "2.52"
compose-bom = "2024.11.00" # BOM 内含 compose-ui 1.7.5 等
activity-compose = "1.9.3"
navigation-compose = "2.8.4"
lifecycle = "2.8.7"
room = "2.6.1"
datastore = "1.1.1"
retrofit = "2.11.0"
okhttp = "4.12.0"
kotlinx-serialization = "1.7.3"
kotlinx-coroutines = "1.9.0"
work = "2.10.0"
camerax = "1.4.0"
splashscreen = "1.0.1"
[libraries]
# Compose BOM:只写 BOM 版本,内部库不写版本
compose-bom = { module = "androidx.compose:compose-bom", version.ref = "compose-bom" }
compose-ui = { module = "androidx.compose.ui:ui" }
compose-ui-tooling-preview = { module = "androidx.compose.ui:ui-tooling-preview" }
compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling" }
compose-material3 = { module = "androidx.compose.material3:material3" }
compose-foundation = { module = "androidx.compose.foundation:foundation" }
# Activity / Lifecycle
androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activity-compose" }
androidx-lifecycle-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "lifecycle" }
androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" }
# Navigation
androidx-navigation-compose = { module = "androidx.navigation:navigation-compose", version.ref = "navigation-compose" }
# Hilt
hilt-android = { module = "com.google.dagger:hilt-android", version.ref = "hilt" }
hilt-compiler = { module = "com.google.dagger:hilt-android-compiler", version.ref = "hilt" }
androidx-hilt-navigation-compose = { module = "androidx.hilt:hilt-navigation-compose", version = "1.2.0" }
# Room
androidx-room-runtime = { module = "androidx.room:room-runtime", version.ref = "room" }
androidx-room-ktx = { module = "androidx.room:room-ktx", version.ref = "room" }
androidx-room-compiler = { module = "androidx.room:room-compiler", version.ref = "room" }
# DataStore
androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "datastore" }
# 网络
retrofit = { module = "com.squareup.retrofit2:retrofit", version.ref = "retrofit" }
retrofit-kotlinx-serialization = { module = "com.squareup.retrofit2:converter-kotlinx-serialization", version.ref = "retrofit" }
okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" }
okhttp-logging = { module = "com.squareup.okhttp3:logging-interceptor", version.ref = "okhttp" }
kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-serialization" }
# 协程
kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinx-coroutines" }
# 后台
androidx-work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version.ref = "work" }
androidx-hilt-work = { module = "androidx.hilt:hilt-work", version = "1.2.0" }
# 相机
androidx-camera-core = { module = "androidx.camera:camera-core", version.ref = "camerax" }
androidx-camera-camera2 = { module = "androidx.camera:camera-camera2", version.ref = "camerax" }
androidx-camera-lifecycle = { module = "androidx.camera:camera-lifecycle", version.ref = "camerax" }
androidx-camera-view = { module = "androidx.camera:camera-view", version.ref = "camerax" }
# 启动
androidx-core-splashscreen = { module = "androidx.core:core-splashscreen", version.ref = "splashscreen" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
android-library = { id = "com.android.library", version.ref = "agp" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
hilt = { id = "com.google.dagger.hilt.android", version.ref = "hilt" }记一件事:Kotlin 2.0.21 必须配 KSP 2.0.21-1.0.27。KSP 版本号是 {kotlin 版本}-{KSP 自己的版本},前缀必须等于你的 Kotlin 版本,否则注解处理直接挂。
四、Compose Compiler:从外挂到内嵌
Kotlin 2.0 之前,Compose 需要一个单独的 Compose Compiler 插件,版本号要和 Kotlin 精确对齐(Kotlin 1.9.0 ↔ Compose Compiler 1.5.0)。这个对齐表是上一代 Android 项目最大的痛苦来源。
Kotlin 2.0.20 起,Compose Compiler 内嵌为 Kotlin 自带插件,通过 org.jetbrains.kotlin.plugin.compose 启用,版本跟着 Kotlin 走。这是 Kotlin 2.0 升级的最大工程红利——你再也不用查那张对齐表了。
所以现代 Android 项目的 Compose 启用方式就是一行:
plugins {
alias(libs.plugins.kotlin-compose) // 就这一行,够了
}不要再用任何 compose-compiler-version 字段。如果你看到一份 2024 之前的 Android 教程让你写 composeOptions { kotlinCompilerExtensionVersion = "..." },那是过时写法。
五、settings.gradle.kts
pluginManagement {
repositories {
google {
content {
includeGroupByRegex("com\\.android.*")
includeGroupByRegex("com\\.google.*")
includeGroupByRegex("androidx.*")
}
}
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "NotedX"
include(":app")FAIL_ON_PROJECT_REPOS 这一行很重要:禁止任何模块自己声明依赖仓库。所有仓库统一在这里管,避免某个三方插件偷偷加一个不可信仓库。
六、根 build.gradle.kts
plugins {
alias(libs.plugins.android-application) apply false
alias(libs.plugins.android-library) apply false
alias(libs.plugins.kotlin-android) apply false
alias(libs.plugins.kotlin-serialization) apply false
alias(libs.plugins.kotlin-compose) apply false
alias(libs.plugins.ksp) apply false
alias(libs.plugins.hilt) apply false
}注意 apply false——根 build.gradle.kts 只是"声明这些插件存在",真正应用在 :app/build.gradle.kts 里。这是 Gradle 多模块项目的标准模式,即便单模块也这么写,后续 20 篇切多模块时不用改这里。
七、:app/build.gradle.kts 完整体
plugins {
alias(libs.plugins.android-application)
alias(libs.plugins.kotlin-android)
alias(libs.plugins.kotlin-serialization)
alias(libs.plugins.kotlin-compose)
alias(libs.plugins.ksp)
alias(libs.plugins.hilt)
}
android {
namespace = "com.notedx"
compileSdk = 35
defaultConfig {
applicationId = "com.notedx"
minSdk = 26
targetSdk = 35
versionCode = 1
versionName = "0.1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
debug {
isMinifyEnabled = false
}
release {
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
buildFeatures {
compose = true
}
packaging {
resources {
excludes += "/META-INF/{AL2.0,LGPL2.1}"
}
}
}
dependencies {
// Compose BOM:统一管理所有 Compose 子库版本
implementation(platform(libs.compose.bom))
androidTestImplementation(platform(libs.compose.bom))
implementation(libs.compose.ui)
implementation(libs.compose.ui.tooling.preview)
implementation(libs.compose.material3)
implementation(libs.compose.foundation)
debugImplementation(libs.compose.ui.tooling)
implementation(libs.androidx.activity.compose)
implementation(libs.androidx.lifecycle.viewmodel.compose)
implementation(libs.androidx.lifecycle.runtime.compose)
implementation(libs.androidx.navigation.compose)
implementation(libs.kotlinx.serialization.json)
implementation(libs.hilt.android)
ksp(libs.hilt.compiler)
implementation(libs.androidx.hilt.navigation.compose)
implementation(libs.androidx.room.runtime)
implementation(libs.androidx.room.ktx)
ksp(libs.androidx.room.compiler)
implementation(libs.androidx.datastore.preferences)
implementation(libs.retrofit)
implementation(libs.retrofit.kotlinx.serialization)
implementation(libs.okhttp)
implementation(libs.okhttp.logging)
implementation(libs.kotlinx.coroutines.android)
implementation(libs.androidx.work.runtime.ktx)
implementation(libs.androidx.hilt.work)
ksp(libs.hilt.compiler)
implementation(libs.androidx.core.splashscreen)
}几个值得专门讲的点:
platform(libs.compose.bom)——BOM(Bill of Materials)模式。Compose 子库都不写版本号,版本由 BOM 决定。升 Compose 时只改libs.versions.toml里的compose-bom一行。ksp(libs.hilt.compiler)——Hilt / Room 的注解处理走 KSP,不再用 KAPT。KAPT 慢且和 K2 兼容性差,2024 起 KSP 是默认答案。buildFeatures { compose = true }——开启 Compose 必须有,但不再需要composeOptions块(因为 Compose Compiler 跟 Kotlin 走了)。jvmTarget = "17"——AGP 8.x 要求 JDK 17。低于 17 编译会直接报错。
八、最小可运行的三个源文件
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:name=".NotedXApp"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:theme="@style/Theme.NotedX"
android:supportsRtl="true"
tools:targetApi="35">
<activity
android:name=".MainActivity"
android:exported="true"
android:theme="@style/Theme.NotedX">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>只有一个 <activity>——这就是单 Activity 心智的物理体现。
NotedXApp.kt(自定义 Application):
package com.notedx
import android.app.Application
class NotedXApp : Application() {
override fun onCreate() {
super.onCreate()
// 进程级初始化挂这里:Hilt(13 篇)、Room(14 篇)、NotificationChannel(17 篇)
}
}MainActivity.kt:
package com.notedx
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContent { MaterialTheme { App() } }
}
}
@Composable
private fun App() {
Scaffold(modifier = Modifier.fillMaxSize()) { inner ->
Text(text = "NotedX online", modifier = Modifier.padding(inner))
}
}40 行不到,覆盖了:ComponentActivity(不是 AppCompatActivity)、enableEdgeToEdge()(API 35 强制)、setContent { }(单 Activity 入口)、MaterialTheme(Material 3)、Scaffold(系统栏内边距处理)。没有 findViewById、没有 setContentView(R.layout.xxx)、没有 XML View。
九、验收
./gradlew :app:assembleDebug # 应当 BUILD SUCCESSFUL,没有 warning
./gradlew :app:installDebug # 装到 API 26+ 模拟器
adb shell am start -n com.notedx/.MainActivity # 拉起后看到 "NotedX online"
adb shell dumpsys package com.notedx | grep -E "minSdk|targetSdk"
# 输出包含 minSdk=26 targetSdk=35打开 Android Studio,Preview 面板不开模拟器也能渲染 UI——这是 Compose 的基本红利。
十、踩坑
坑 1:照搬别人 build.gradle 时把 KAPT 也搬过来。KAPT 在 K2 编译器下被官方明确不推荐,与 KSP 共存还会导致同一注解被处理两次。Hilt / Room / Moshi 全部走 KSP,项目里不应出现一行 kapt(...)。
坑 2:用裸版本字符串。implementation("com.squareup.retrofit2:retrofit:2.11.0") 这种写法,半年后某个库需要升级时你要全项目搜替换,极其容易漏。Version Catalog 是唯一答案。
坑 3:Compose Compiler 旧写法。如果在 :app/build.gradle.kts 里看到 composeOptions { kotlinCompilerExtensionVersion = "..." },删掉。Kotlin 2.0.20+ 全靠 kotlin-compose 插件,不需要这个块。
坑 4:mavenCentral() 写在每个模块里。FAIL_ON_PROJECT_REPOS 设了之后这种写法直接报错。这是好事——它强制你把仓库集中在 settings.gradle.kts。
坑 5:compileSdk 比 targetSdk 低。compileSdk 决定"源码能看见哪些 API",targetSdk 决定"运行时按哪个版本行为对待"。两者通常应当一致,只有少数情况(比如想用新 API 但不想被新行为变更影响)才分开。新人 99% 应当让两者相等。
坑 6:CI 上跑 assembleRelease 报内存不足。Gradle 默认堆内存 1 GB,Compose / R8 编译时常常爆。gradle.properties 加:
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.configuration-cache=true其中 configuration-cache=true 能把 configuration 阶段缓存住,日常增量编译能省一半时间。
坑 7:升级 Kotlin 忘了同步升 KSP。Kotlin 2.0.21 配 KSP 2.0.21-1.0.27,Kotlin 2.0.20 配 KSP 2.0.20-1.0.25——前缀必须等于你的 Kotlin 版本。错配的症状是构建报 "KSP plugin version mismatch",非常明显。
下一篇 03-Kotlin2.0语言心智.md,把 Kotlin 2.0(K2 编译器)写 Android 时真正用得着的东西讲清楚:data class / 空安全 / lateinit / by lazy / 扩展函数 / 委托 / sealed / inline / reified / 范围与作用域函数。不会讲"Kotlin 全特性",只讲在后续 19 篇里反复出现的那些。