Cấu trúc Build Files trong Android
Gradle builds cho Android được phân chia qua nhiều file trong project. Hiểu rõ vai trò của từng file giúp bạn cấu hình và debug build một cách hiệu quả.
Sơ đồ tổng quan
MyApp/
├── .gradle/ # Gradle cache (không chỉnh sửa!)
├── .idea/ # Android Studio metadata
├── gradle/
│ ├── wrapper/
│ │ ├── gradle-wrapper.jar # Gradle bootstrapping
│ │ └── gradle-wrapper.properties
│ └── libs.versions.toml # Version Catalog
├── app/ # Module chính
│ ├── src/
│ │ ├── main/ # Source code chính
│ │ ├── test/ # Unit tests
│ │ └── androidTest/ # Instrumented tests
│ ├── build.gradle.kts # Module-level build file
│ └── proguard-rules.pro # R8 configuration
├── build.gradle.kts # Project-level build file
├── settings.gradle.kts # Project settings
├── gradle.properties # Gradle configuration
├── gradlew # Gradle wrapper (Linux/Mac)
├── gradlew.bat # Gradle wrapper (Windows)
└── local.properties # Local machine config (gitignore!)Chi tiết từng file
1. settings.gradle.kts
Mục đích: Cấu hình Gradle initialization - xác định modules và repositories.
// settings.gradle.kts
pluginManagement {
repositories {
google() // Google's Maven repository
mavenCentral() // Maven Central
gradlePluginPortal() // Gradle plugins
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "MyApp"
// Khai báo các modules
include(":app")
include(":core:network")
include(":feature:home")| Block | Mục đích |
|---|---|
pluginManagement | Nơi tải plugins |
dependencyResolutionManagement | Nơi tải dependencies |
include() | Khai báo các subprojects/modules |
💡 Mẹo:
RepositoriesMode.FAIL_ON_PROJECT_REPOSđảm bảo tất cả repositories được khai báo tập trung tại đây, không phải trong từng module.
2. build.gradle.kts (Project-level)
Mục đích: Khai báo plugins sử dụng trong toàn bộ project.
Vị trí: Root folder (/build.gradle.kts)
// build.gradle.kts (Project-level)
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.compose) apply false
alias(libs.plugins.hilt) apply false
alias(libs.plugins.ksp) apply false
}⚠️ Quan trọng: Sử dụng
apply falseđể khai báo plugins nhưng chưa áp dụng. Các module sẽ tự chọn plugins cần thiết.
Tại sao cần file này?
- Đảm bảo tất cả modules sử dụng cùng phiên bản plugin
- Tránh conflict khi các modules khai báo versions khác nhau
3. build.gradle.kts (Module-level)
Mục đích: Cấu hình build cho một module cụ thể.
Vị trí: Trong thư mục module (/app/build.gradle.kts)
// app/build.gradle.kts
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.hilt)
alias(libs.plugins.ksp)
}
android {
namespace = "com.example.myapp"
compileSdk = 35
defaultConfig {
applicationId = "com.example.myapp"
minSdk = 24
targetSdk = 35
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
debug {
isDebuggable = true
applicationIdSuffix = ".debug"
}
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
buildConfig = true
}
}
dependencies {
// Core Android
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
// Compose
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.ui)
implementation(libs.androidx.material3)
implementation(libs.androidx.activity.compose)
// DI
implementation(libs.hilt.android)
ksp(libs.hilt.compiler)
// Testing
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
}Các block quan trọng
| Block | Mục đích |
|---|---|
plugins {} | Áp dụng plugins cho module này |
android {} | Cấu hình Android-specific |
android.defaultConfig {} | Cấu hình mặc định cho tất cả build variants |
android.buildTypes {} | Cấu hình debug, release, etc. |
android.buildFeatures {} | Bật/tắt features (Compose, BuildConfig, etc.) |
dependencies {} | Khai báo thư viện sử dụng |
4. libs.versions.toml (Version Catalog)
Mục đích: Quản lý versions của dependencies và plugins tập trung.
Vị trí: /gradle/libs.versions.toml
[versions]
kotlin = "2.0.21"
agp = "8.7.2"
compose-bom = "2024.11.00"
core-ktx = "1.15.0"
lifecycle = "2.8.7"
hilt = "2.52"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "core-ktx" }
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "compose-bom" }
androidx-ui = { group = "androidx.compose.ui", name = "ui" }
androidx-material3 = { group = "androidx.compose.material3", name = "material3" }
hilt-android = { group = "com.google.dagger", name = "hilt-android", version.ref = "hilt" }
hilt-compiler = { group = "com.google.dagger", name = "hilt-compiler", version.ref = "hilt" }
[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-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
hilt = { id = "com.google.dagger.hilt.android", version.ref = "hilt" }💡 Mẹo: Xem chi tiết về Version Catalog trong bài Version Catalog.
5. gradle.properties
Mục đích: Cấu hình Gradle build environment.
# gradle.properties
# JVM memory allocation
org.gradle.jvmargs=-Xmx4096m -Dfile.encoding=UTF-8
# Enable parallel execution
org.gradle.parallel=true
# Enable build caching
org.gradle.caching=true
# Configure on demand (for multi-module)
org.gradle.configureondemand=true
# AndroidX migration
android.useAndroidX=true
# Non-transitive R classes (recommended)
android.nonTransitiveRClass=true
# Kotlin code style
kotlin.code.style=official
# Disable Jetifier (if not using old Support Library)
android.enableJetifier=false| Property | Mô tả |
|---|---|
org.gradle.jvmargs | Memory cho Gradle daemon |
org.gradle.parallel | Build các modules song song |
org.gradle.caching | Cache task outputs |
android.nonTransitiveRClass | R class không chứa resources từ dependencies |
6. Gradle Wrapper
Mục đích: Đảm bảo mọi người dùng cùng phiên bản Gradle.
Files:
gradlew(Linux/Mac) vàgradlew.bat(Windows) - Shell scriptsgradle/wrapper/gradle-wrapper.jar- Bootstrapping executablegradle/wrapper/gradle-wrapper.properties- Cấu hình version
# gradle-wrapper.properties
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.9-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists📝 Lưu ý: Luôn sử dụng
./gradlewthay vìgradlecommand để đảm bảo consistent builds.
7. local.properties
Mục đích: Cấu hình máy local (SDK path, NDK path).
# local.properties
sdk.dir=/Users/username/Library/Android/sdk🚨 Chú ý: KHÔNG commit file này lên Git! File này chứa paths cụ thể của máy local và được tự động tạo bởi Android Studio.
8. proguard-rules.pro
Mục đích: Cấu hình R8 (code shrinking, obfuscation).
# proguard-rules.pro
# Keep model classes for serialization
-keep class com.example.app.data.model.** { *; }
# Keep Retrofit interfaces
-keep,allowobfuscation interface * {
@retrofit2.http.* <methods>;
}
# Debug: print removed code
-printusage removed-code.txtSource Sets
Source sets định nghĩa nơi chứa source code và resources cho các build variants.
app/src/
├── main/ # Source chung cho tất cả variants
│ ├── java/ # Kotlin/Java code
│ ├── res/ # Resources
│ └── AndroidManifest.xml
├── debug/ # Source riêng cho debug build
│ └── java/
├── release/ # Source riêng cho release build
│ └── res/
├── test/ # Unit tests (chạy trên JVM)
│ └── java/
└── androidTest/ # Instrumented tests (chạy trên device)
└── java/Thứ tự ưu tiên
Khi có file trùng tên, Gradle merge theo thứ tự:
Build variant source set > Build type source set > Product flavor > mainVí dụ với variant demoDebug:
src/demoDebug/(nếu có)src/debug/src/demo/src/main/
Tóm tắt
| File | Mục đích | Scope |
|---|---|---|
settings.gradle.kts | Modules, repositories | Toàn project |
build.gradle.kts (root) | Plugin versions | Toàn project |
build.gradle.kts (module) | Dependencies, config | Một module |
libs.versions.toml | Version management | Toàn project |
gradle.properties | Build environment | Toàn project |
local.properties | Local machine paths | Local only |
proguard-rules.pro | Code shrinking rules | Một module |