Phần lớn lỗi build Android không nằm ở code. Nó nằm ở ba con số version không khớp nhau: Gradle, Android Gradle Plugin (AGP) và Kotlin. Sửa một số, Gradle sync đỏ; nâng số khác, R8 hoặc KSP gãy. Hiểu Gradle trước hết là hiểu file nào chịu trách nhiệm cho việc gì.
Bài này dùng toolchain tháng 11/2026: Gradle 9.9.0, AGP 9.5.1, Kotlin 2.4.21, compileSdk 36. Mục tiêu là bạn mở được build.gradle.kts, bỏ dòng thừa và build release mà không phải xóa cache.
Mục lục
Cập nhật 2026: năm thay đổi so với tutorial cũ
- AGP 9.5 đòi Gradle 9.6 trở lên. Bài dùng wrapper 9.9.0.
- Kotlin DSL và version catalog là mặc định. Groovy chỉ còn ở dự án cũ.
- KSP2 thay KAPT. Room, Hilt và Moshi dùng KSP2; KAPT là legacy, chậm vì sinh stub Java.
compileđã bị xóa từ Gradle 7; tutorial còncompilesẽ fail ở bước cấu hình.- Configuration cache và build cache nên bật. JDK 17 là baseline của AGP 9.5.
Gradle làm gì trong một build Android
Một build Android là chuỗi bước: biên dịch Kotlin/Java, chuyển sang DEX, xử lý resource và manifest, đóng gói APK/AAB, ký, test, tối ưu bằng R8. Gradle điều phối chuỗi đó; AGP dạy Gradle các bước riêng của Android.
| Lớp | Bản 2026 | Việc nó làm |
|---|---|---|
| Gradle | 9.9.0 | Đọc script, dựng task graph, chạy task, quản lý cache và dependency |
| AGP | 9.5.1 | Sinh task Android: merge manifest, DEX, package, signing, lint |
| Kotlin | 2.4.21 | Compiler và plugin Kotlin; Compose compiler đi kèm |
Gradle không biết Android; nó biết task nào phụ thuộc task nào. Khi chạy assembleDebug, Gradle hỏi AGP danh sách task rồi chạy theo thứ tự. Lỗi trong build.gradle.kts thường xuất hiện trước khi compiler Kotlin chạy.
Wrapper: version thuộc về repo, không thuộc về máy bạn
Commit cả bốn file gradlew, gradlew.bat, gradle-wrapper.jar và gradle-wrapper.properties. Chúng khóa bản Gradle cho team và CI; không cần cài toàn cục. Kiểm tra và nâng bằng:
./gradlew --version
./gradlew wrapper --gradle-version 9.9.0 --distribution-type bin
Dòng JVM: trong kết quả phải là 17.x. AGP 9.5 lấy JDK 17 làm baseline; Gradle chạy được trên JDK 21 hoặc 25, nhưng jvmTarget của app vẫn nên là 17. Nếu JAVA_HOME trỏ về JDK 8 hoặc 11, bạn gặp Unsupported class file major version hoặc thông báo AGP cần Java 17. Cách cài JDK và SDK có trong bài thiết lập môi trường.
Những file cấu hình bạn thực sự sửa
EvotekNotes/
├── gradle/
│ ├── libs.versions.toml
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle.kts
├── build.gradle.kts
├── gradle.properties
└── app/
└── build.gradle.kts
settings.gradle.kts
File này đọc trước mọi file khác: khai báo module và repository. Repository khai báo một lần ở đây; khai báo trong module bị FAIL_ON_PROJECT_REPOS chặn.
// File: settings.gradle.kts
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "EvotekNotes"
include(":app")
build.gradle.kts ở root
Root chỉ khai báo plugin ở mức dự án, chưa áp dụng cho module. Không cần buildscript { classpath ... } như tutorial Groovy cũ; plugins DSL lấy version từ catalog.
// File: build.gradle.kts
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.kotlin.android) apply false
alias(libs.plugins.kotlin.compose) apply false
}
gradle/libs.versions.toml
Catalog là nguồn số duy nhất: đổi AGP chỉ sửa một dòng. Alias có gạch ngang thành accessor dấu chấm: androidx-compose-bom là libs.androidx.compose.bom.
# File: gradle/libs.versions.toml
[versions]
agp = "9.5.1"
kotlin = "2.4.21"
composeBom = "2026.09.00"
lifecycle = "2.11.0"
room = "2.8.5"
[libraries]
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }
androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
BOM 2026.09.00 quyết định version Compose (Compose 1.12.1, Material3 1.4.0), nên đừng pin thêm material3. Plugin Compose phải cùng version Kotlin.
app/build.gradle.kts: module hoàn chỉnh
File này chứa gần như toàn bộ cấu hình build: định danh, SDK, feature, ký, build type, flavor, JVM target và dependency.
// File: app/build.gradle.kts
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
}
android {
namespace = "vn.evotek.notes"
compileSdk = 36
defaultConfig {
applicationId = "vn.evotek.notes"
minSdk = 24
targetSdk = 36
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildFeatures {
compose = true
buildConfig = true
}
signingConfigs {
val storePath = providers.environmentVariable("EVOTEK_KEYSTORE").orNull
if (storePath != null) {
create("release") {
storeFile = file(storePath)
storePassword = providers.environmentVariable("EVOTEK_STORE_PASSWORD").orNull
keyAlias = providers.environmentVariable("EVOTEK_KEY_ALIAS").orNull
keyPassword = providers.environmentVariable("EVOTEK_KEY_PASSWORD").orNull
}
}
}
buildTypes {
debug {
applicationIdSuffix = ".debug"
versionNameSuffix = "-debug"
}
release {
isMinifyEnabled = true
isShrinkResources = true
signingConfig = signingConfigs.findByName("release")
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
flavorDimensions += "env"
productFlavors {
create("dev") {
dimension = "env"
applicationIdSuffix = ".dev"
buildConfigField("String", "API_BASE_URL", "\"https://dev.api.evotek.vn\"")
}
create("prod") {
dimension = "env"
buildConfigField("String", "API_BASE_URL", "\"https://api.evotek.vn\"")
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
kotlin {
compilerOptions {
jvmTarget.set(JvmTarget.JVM_17)
}
}
dependencies {
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.compose.ui)
implementation(libs.androidx.compose.material3)
implementation(libs.androidx.compose.ui.tooling.preview)
debugImplementation(libs.androidx.compose.ui.tooling)
implementation(libs.androidx.lifecycle.runtime.compose)
}
namespace sinh R class; applicationId là định danh trên Play. compileSdk = 36 build against Android 16; AGP 9.5 hỗ trợ tối đa 37, nhưng 37 là Android 17 beta. targetSdk = 36 đáp ứng yêu cầu Play từ 31/08/2026.
buildFeatures.compose = true bật Compose; buildConfig = true bắt buộc nếu dùng buildConfigField, vì từ AGP 8 cờ này mặc định tắt. compileOptions và jvmTarget cùng là 17; lệch một bên sinh lỗi Inconsistent JVM-target compatibility.
AGP, Gradle và Kotlin: ba version, một dây chuyền
| Thành phần | Bản đang dùng | Ràng buộc cứng |
|---|---|---|
| Gradle | 9.9.0 | AGP 9.5 cần tối thiểu 9.6.0 |
| AGP | 9.5.1 | JDK 17, compileSdk tối đa 37, Build Tools 36.0.0 |
| Kotlin | 2.4.21 | Compose plugin cùng bản; KSP phải khớp |
Gradle là engine, AGP là plugin, Kotlin là compiler. Không có cơ chế tự đồng bộ; mỗi bên chỉ kiểm tra vài ràng buộc và báo lỗi khi vi phạm.
Mismatch thường gặp: Gradle 8.14.6 với AGP 9.5 báo cần Gradle 9.6.0; JDK 11 báo cần Java 17; Compose plugin lệch Kotlin; KSP lệch Kotlin; compileOptions 17 còn jvmTarget 1.8. Thông báo chỉ đúng cặp version, không chỉ đúng file.
Nâng theo thứ tự: wrapper, AGP, Kotlin, plugin Compose, KSP. Chạy assembleDebug sau mỗi bước và commit riêng; nâng cả bốn trong một commit biến một lỗi thành bốn lỗi chồng nhau.
Dependencies: implementation, api và ksp
| Cấu hình | Phạm vi | Dùng khi |
|---|---|---|
implementation |
Module hiện tại | Mặc định cho gần như mọi thư viện |
api |
Module hiện tại và module phụ thuộc | Library module, khi type lộ ra public API |
compileOnly |
Chỉ lúc biên dịch | API chỉ cần compile, không đóng gói |
runtimeOnly |
Chỉ lúc chạy | Implementation của interface |
ksp |
Sinh code lúc build | Room, Hilt, Moshi với KSP2 |
testImplementation |
Source set test | JUnit, thư viện chỉ dùng cho unit test |
api trong app gần như vô nghĩa; nó chỉ quan trọng ở library module. Lạm dụng api làm build chậm vì Gradle biên dịch lại nhiều module. compile/testCompile/androidTestCompile đã bị xóa; thay bằng implementation/testImplementation/androidTestImplementation.
KSP2 là lựa chọn chính thức cho annotation processing. Thêm KSP sau khi chốt version khớp Kotlin 2.4.21:
// app/build.gradle.kts — thêm alias KSP vào plugins
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.ksp)
}
dependencies {
implementation(libs.androidx.room.runtime)
ksp(libs.androidx.room.compiler)
}
ksp {
arg("room.schemaLocation", "$projectDir/schemas")
}
Đừng chép số KSP từ bài này: 2.3.13 có lỗi concurrency, bản khớp Kotlin 2.4.x chưa được xác minh. Chọn bản đúng từ release notes rồi thêm vào catalog. KAPT vẫn chạy nhưng đã là legacy; đừng chuyển dự án ổn định chỉ để đổi tool.
Build type, flavor và ký release
Build type quyết định build như thế nào: debug có debuggable, release bật R8 và ký. Flavor quyết định bản nào: app id, tên, server, SDK đối tác. Variant là tích của hai chiều; cấu hình trong bài tạo devDebug, devRelease, prodDebug, prodRelease, mỗi variant có task assemble, lint và test riêng.
Đừng đặt mật khẩu keystore trong build.gradle.kts hay gradle.properties rồi commit. Đoạn signing đọc biến môi trường qua providers.environmentVariable: CI truyền secret, máy local thiếu biến thì bỏ qua release. Keystore và keystore.properties phải nằm trong .gitignore; debug tự ký bằng debug key.
applicationIdSuffix đổi identity trên Play, nên chỉ dùng cho dev và debug. Đừng gắn suffix cho prodRelease. buildConfigField sinh hằng trong BuildConfig, dùng cho base URL; đừng dùng nó cho API key vì giá trị nằm thẳng trong APK.
Chạy task: lệnh nào làm gì
| Lệnh | Việc nó làm | Khi dùng |
|---|---|---|
./gradlew :app:assembleDebug |
Build APK debug | Chạy thử trên máy thật hoặc emulator |
./gradlew :app:bundleRelease |
Build AAB release, chạy R8, ký nếu có signingConfig | Upload Google Play |
./gradlew :app:lint |
Android Lint trên variant mặc định | Trước khi merge; xem thêm Ktlint vs Detekt |
./gradlew test |
Chạy unit test trên JVM | Mỗi lần đổi logic, không cần thiết bị |
./gradlew :app:dependencies |
In cây dependency theo configuration | Gỡ conflict hoặc tìm thư viện kéo version lạ |
./gradlew :app:installDebug |
Build và cài bản debug | Test nhanh không mở Android Studio |
clean không sửa lỗi build: nó xóa output và buộc build nguội. Chỉ dùng khi output hỏng; nếu nghi task không chạy lại, dùng --rerun-tasks. Build đầu sau khi đổi version luôn chậm. Cách chạy app và đọc lỗi sync có trong bài ứng dụng đầu tiên.
Build cache và configuration cache
Build cache lưu output task và dùng lại khi input không đổi. Bật bằng org.gradle.caching=true; trên CI thêm remote cache để máy sạch hưởng kết quả pipeline trước. Cache chỉ hiệu quả khi task khai báo input/output đúng.
Configuration cache lưu pha cấu hình, nên lần sau Gradle không đọc lại toàn bộ script. Bật bằng org.gradle.configuration-cache=true. Cache nhớ biến môi trường, file, thư mục, cả output của git; giá trị đổi thì cache miss và Gradle cấu hình lại. Nếu script gọi git rev-parse, đọc timestamp hoặc file(...).exists() mỗi build, bạn thấy “full rebuild” lặp lại dù task không đổi.
Dùng providers.environmentVariable, providers.gradleProperty và providers.fileContents thay cho đọc trực tiếp; Gradle theo dõi chúng như input. Tránh afterEvaluate và version động kiểu 1.+. Nếu plugin chưa hỗ trợ configuration cache, tắt tạm bằng --no-configuration-cache rồi mở lại sau.
R8 và minify cho release
Release bật isMinifyEnabled và isShrinkResources. R8 rút gọn code, đổi tên và loại resource; APK/AAB nhỏ hơn nhưng có thể gãy nếu code dùng reflection hoặc tên class qua chuỗi. Thêm keep rule vào proguard-rules.pro, chỉ đúng phần cần thiết — -keep class ** { *; } vô hiệu hóa gần như toàn bộ lợi ích của R8.
Luôn test bản release: bật R8 trên debug không tái hiện lỗi vì debug không minify. Giữ mapping.txt trong build/outputs/mapping/<variant>/ và upload lên Play để crash stack trace được deobfuscate. Nếu R8 báo thiếu class, đọc rule nào bị thiếu thay vì tắt minify.
Sáu lỗi hay gặp
- Tutorial Groovy đời cũ.
buildscriptclasspath,allprojectsrepositories,compile,applicationVariants.allvàkotlinOptionsđều cũ hoặc đã xóa. Chuyển sangpluginsDSL, repository trongsettingsvàcompilerOptions. - Hard-code version. Cùng số AGP nằm ở root, app và README sẽ lệch sau vài tháng. Đưa vào catalog; Compose để BOM quyết định.
- Dùng
compile. Đã bị xóa từ Gradle 7. Đổi sangimplementation;apichỉ khi xuất type ra ngoài module. - Secret trong build file. Mật khẩu keystore, token, API key trong
gradle.propertiessẽ vào git. Dùng biến môi trường hoặc secret store CI; keystore không commit. - Configuration cache miss. Đọc
git, timestamp, file tạm ở pha cấu hình làm cache vô hiệu. Dùngproviders, bỏafterEvaluate, tránh version động. - Lạm dụng flavor. Mỗi flavor nhân với mỗi build type, kéo theo lint, test và CI. Nếu chỉ khác server,
buildConfigFieldhoặc remote config đủ; flavor dành cho khác biệt về app id hoặc SDK đối tác.
Khi nào dùng gì
| Nhu cầu | Dùng | Tránh |
|---|---|---|
| Khác debug và release | buildTypes |
Tạo flavor debug/release thủ công |
| Khác app id, server, SDK đối tác | productFlavors |
Nhân flavor cho từng biến cấu hình nhỏ |
| Quản lý version | Version catalog và BOM | Số version rải trong nhiều file |
| Bí mật và ký | Biến môi trường, CI secret | gradle.properties đã commit |
Nhìn trước 2027
Kotlin 2.5.0 dự kiến ra tháng 12/2026; kiểm tra KSP và Compose compiler trước khi nâng. Android 17 (API 37) đang beta; khi stable, compileSdk mới lên 37 cùng một đợt AGP mới. Hãy để wrapper và catalog là nơi duy nhất chứa số version.
Checklist trước khi commit
./gradlew --version: Gradle 9.9.0, JVM 17.- Wrapper trong git, properties trỏ đúng 9.9.0.
- Catalog chứa AGP, Kotlin, BOM; module không hard-code version.
assembleDebugvàtestchạy sạch.bundleReleasetạo AAB đã ký từ secret CI.lintsạch; configuration cache không miss liên tục.
Đọc tiếp roadmap Android để đặt phần build này vào đúng vị trí trong lộ trình, hoặc quay lại bài trước nếu bạn chưa dựng xong môi trường.



