Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

เร่งความเร็ว Gradle Build ใน Android Studio


Gradle Build คืออะไร?

Gradle เป็น Build Automation Tool ที่ Android Studio ใช้คอมไพล์ โค้ด Java/Kotlin, XML, Resource ให้กลายเป็น APK/AAB การ Build ช้าเป็นปัญหาหลักที่ทำให้ Developer เสียเวลารอ

Gradle Sync vs Build

  • Gradle Sync: ดาวน์โหลด Dependency, Parse Scripts, Configure Project (รันตอนเปิดโปรเจกต์/แก้ build.gradle)
  • Gradle Build: Compile, Dex, Merge Resources, Package APK (รันตอนกด Run/Debug/Build APK)

การตั้งค่าเร่งความเร็ว (Configuration)

1. gradle.properties (Project Root) - สำคัญที่สุด

# Project-wide Gradle settings
# Enable Daemon (คง Process ไว้รอ Build ถัดไป)
org.gradle.daemon=true

# Parallel Execution (Build Module หลายตัวพร้อมกัน)
org.gradle.parallel=true

# Configure on Demand (Configure Module ที่จำเป็นเท่านั้น)
org.gradle.configureondemand=true

# JVM Arguments - เพิ่ม Heap Size
# -Xmx: Max Heap (เพิ่มตาม RAM เครื่อง 4GB=2g, 8GB=4g, 16GB=8g)
# -XX:MaxMetaspaceSize: Metaspace (Class Metadata)
# -Dfile.encoding: Encoding
org.gradle.jvmargs=-Xmx4096m -XX:MaxMetaspaceSize=1024m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

# Caching
org.gradle.caching=true
# File system watching (Linux/macOS/Windows 10+)
org.gradle.vfs.watch=true

# Kotlin Daemon (ถ้าใช้ Kotlin)
kotlin.daemon.enabled=true
kotlin.parallel.tasks.enabled=true

2. Android Studio Settings (UI)

File → Settings → Build, Execution, Deployment → Gradle

  • ☑ Offline work - ใช้ Cache Dependency ไม่โหลดจาก Network (เร็วมาก แต่ต้อง Sync ออนไลน์ก่อน)
  • ☑ Gradle JVM - ใช้ JDK 17/21 (เร็วกว่า JDK 8/11)

File → Settings → Build, Execution, Deployment → Compiler

  • ☑ Build project automatically
  • ☑ Compile independent modules in parallel
  • ☑ Configuration on demand (ซ้ำกับ gradle.properties)

3. build.gradle (Module: app) - Optimization

android {
    // ...
    
    // 1. ปิด PNG Crunching (เร็วขึ้นเล็กน้อย)
    aaptOptions {
        cruncherEnabled = false // Debug build
    }

    // 2. กำหนด Version Code/Name แบบ Static (หลีกเลี่ยงการคำนวณ Dynamic)
    defaultConfig {
        versionCode 1
        versionName "1.0"
    }

    // 3. ปิด Unused Resource Shrinking ใน Debug (เร็วขึ้น)
    buildTypes {
        debug {
            minifyEnabled false
            shrinkResources false
            // ใช้ ApplicationIdSuffix แทนการ Build แยก
            applicationIdSuffix ".debug"
            versionNameSuffix "-debug"
            // ใช้ Proguard Rules เฉพาะ Release
        }
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    // 4. Dex Options (Legacy - AGP 8.0+ จัดการเอง)
    // dexOptions { 
    //     maxProcessCount 4 
    //     javaMaxHeapSize "4g" 
    // }

    // 5. Avoid Legacy MultiDex (ใช้ Native MultiDex - API 21+)
    // defaultConfig { multiDexEnabled true } // API 21+ ไม่ต้อง MultiDex
}

dependencies {
    // 6. ใช้ Implementation แทน Api/Compile (การแยก Dependency Graph)
    implementation 'androidx.core:core-ktx:1.12.0'
    
    // 7. Constraint Version ใน build.gradle (Project) หรือ Version Catalog (TOML)
}

4. ใช้ Version Catalog (gradle/libs.versions.toml) - Gradle 7+

[versions]
agp = "8.3.0"
kotlin = "1.9.20"
coreKtx = "1.12.0"
material = "1.11.0"
glide = "4.16.0"

[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
material = { group = "com.google.android.material", name = "material", version.ref = "material" }
glide = { group = "com.github.bumptech.glide", name = "glide", version.ref = "glide" }
glide-compiler = { group = "com.github.bumptech.glide", name = "compiler", version.ref = "glide" }

[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }

ใช้ใน Module: `implementation libs.androidx.core.ktx`

Hardware & Environment Optimization

FactorRecommendation
RAM16GB+ (8GB ขั้นต่ำ)
CPUMulti-core (8 cores+), High Single-thread Score
StorageNVMe SSD (ไม่ใช่ HDD/SATA SSD)
OSLinux/macOS เร็วกว่า Windows (File System)
JDKJDK 17/21 (LTS) - เร็วกว่า JDK 8/11 มาก
Anti-virusExclude Project Folder, .gradle, .android

Advanced Techniques

1. Configuration Cache (Gradle 7.0+)

# gradle.properties
org.gradle.configuration-cache=true
# รัน: ./gradlew --configuration-cache

Cache การ Configure Project ทั้งหมด Build ถัดไปเร็วมาก (Skip Configuration Phase)

2. Build Cache (Local + Remote)

# gradle.properties
org.gradle.caching=true
# Remote Cache (Team/Enterprise) - ต้องมี Server
# org.gradle.caching.remote.url=https://cache.company.com
# org.gradle.caching.remote.username=...
# org.gradle.caching.remote.password=...

3. Profile Build

# ดู Dependency Tree
./gradlew app:dependencies --configuration debugRuntimeClasspath

# หา Duplicate/Unused
./gradlew app:dependencyInsight --dependency  --configuration debugRuntimeClasspath

5. Modularization (Dynamic Feature / Library Modules)

  • แยก Module ที่ไม่เกี่ยวข้อง → Build แยกได้ (Parallel)
  • ใช้ Dynamic Feature Module สำหรับฟีเจอร์ที่ไม่จำเป็นตอนติดตั้ง

Troubleshooting ปัญหา Build ช้า

อาการสาเหตุที่เป็นไปได้แก้ไข
Sync ช้ามากNetwork, Repository มาก, Dependency ConflictOffline Work, Version Catalog, Consolidate Repos
Compile Java/Kotlin ช้าHeap น้อย, Daemon ตาย, Annotation Processor เยอะเพิ่ม Xmx, KSP แทน KAPT, Incremental Compilation
Dex/Transform ช้าMultiDex, Library ใหญ่, MinifyNative MultiDex (API 21+), R8 Full Mode
Link/Merge Resources ช้าResource เยอะ, PNG CrunchaaptOptions.cruncherEnabled=false (Debug), WebP
Build ทุกครั้ง Full BuildConfiguration Cache ปิด, File Watch ปิดเปิด Configuration Cache, VFS Watch

สรุป Checklist เร่ง Build

  1. ✅ ตั้งค่า gradle.properties (Daemon, Parallel, JVM Args, Caching)
  2. ✅ เปิด Offline Work ใน Settings
  3. ✅ ใช้ JDK 17/21
  4. ✅ ใช้ Version Catalog (TOML)
  5. ✅ ใช้ Implementation ไม่ใช่ Api
  6. ✅ Modularization โปรเจกต์ใหญ่
  7. ✅ เปิด Configuration Cache (Gradle 7+)
  8. ✅ Profile Build หา Bottleneck จริง
  9. ✅ Hardware: RAM 16GB+, NVMe SSD, Multi-core CPU