Gradle basics and build variants
Why it matters
- Every release, every CI run and every "it only crashes in release" bug goes through Gradle. You cannot debug a build you do not understand.
- Build types and flavors decide which API URL, app id and shrinking rules a build uses. A mistake here reaches real users.
- Dependency conflicts and slow builds are daily pain on real teams. Knowing the tools to inspect them saves hours.
- Interviews ask about
compileSdkvstargetSdk,implementationvsapi, and why release builds behave differently.
The simple explanation
Think of a factory with a blueprint.
- The blueprint is your build files. You write what the product is and which parts it needs.
- The supplier list is the version catalog. One list says which part comes in which version.
- The factory can make different models from one blueprint: a test model with labels everywhere (debug) and a polished shipping model (release).
- You can also ask for different editions, such as a free edition and a paid one (flavors).
Gradle runs in three phases:
| Phase | What happens |
|---|---|
| Initialization | Reads settings.gradle.kts and decides which modules exist |
| Configuration | Runs each module's build file and builds the task graph |
| Execution | Runs only the tasks needed, skipping those whose inputs did not change |
The real names:
| Term | Meaning |
|---|---|
| Build type | How it is built: debug, release, or your own such as staging |
| Product flavor | What it is built for: free, paid, demo. Needs a flavorDimensions entry |
| Build variant | One flavor plus one build type, for example freeDebug |
minSdk | Lowest Android version the app installs on |
targetSdk | The Android version the app says it was tested on. It turns on that version's behavior changes |
compileSdk | The API level you compile against. It controls which APIs you can call, not where the app runs |
Notes
compileSdkis a compile-time choice. Raising it does not change runtime behavior. RaisingtargetSdkdoes, so test again.namespaceinbuild.gradle.ktssets the package forRand generated code.applicationIdis the identity on the device and in the Play Store. They can differ.- debug vs release: debug is debuggable and signed with a debug key. Release should be minified (
isMinifyEnabled = true) and signed with your upload key. - R8 shrinks, optimizes and obfuscates. Code found through reflection needs keep rules, or it can break only in release.
isShrinkResources = trueremoves unused resources. It needs minification turned on.- Configurations:
implementation: used by this module, hidden from modules that depend on it.api: also exposed to consumers (needs thejava-libraryplugin or an Android library module).debugImplementation,testImplementation,androidTestImplementation: only for that variant or test set.ksp(...): annotation processors that use KSP. Prefer KSP overkaptfor Room, Hilt and Moshi codegen.
- A version catalog (
gradle/libs.versions.toml) has[versions],[libraries]and[plugins]. In build files you writelibs.androidx.core.ktx. Dashes in the name become dots. - When two libraries need different versions of one dependency, Gradle picks the highest version in the graph by default.
- Never hardcode keystore passwords in a build file. Read them from environment variables or untracked properties, especially on CI.
- Useful commands:
./gradlew assembleDebug,./gradlew :app:dependencies,./gradlew :app:dependencyInsight --dependency okhttp --configuration releaseRuntimeClasspath,./gradlew tasks. - Exact plugin setup changes between Android Gradle Plugin versions. For a new project, copy the structure from the New Project wizard of your Studio version.
Code example
A module with two build types, two flavors and a catalog. Versions are not shown: they live in the catalog.
// app/build.gradle.kts
plugins {
alias(libs.plugins.android.application)
// AGP 9 compiles Kotlin itself. On AGP 8, also apply alias(libs.plugins.kotlin.android).
alias(libs.plugins.ksp)
}
android {
namespace = "com.example.shop"
compileSdk = 36 // use the current stable API level
defaultConfig {
applicationId = "com.example.shop"
minSdk = 24
targetSdk = 36
}
buildFeatures { buildConfig = true } // BuildConfig is off by default
flavorDimensions += "tier"
productFlavors {
create("free") { dimension = "tier"; applicationIdSuffix = ".free" }
create("paid") { dimension = "tier" }
}
buildTypes {
debug {
applicationIdSuffix = ".debug" // install beside release
buildConfigField("String", "API_URL", "\"https://staging.example.com/\"")
}
release {
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
buildConfigField("String", "API_URL", "\"https://api.example.com/\"")
}
}
}
dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.okhttp)
implementation(libs.room.runtime)
ksp(libs.room.compiler)
debugImplementation(libs.leakcanary)
}# gradle/libs.versions.toml (one line per entry, versions omitted here)
[versions]
okhttp = "x.y.z"
[libraries]
okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" }Variants made here: freeDebug, freeRelease, paidDebug, paidRelease. Note that the code keeps one rule: secrets are not in this file.
In production
- Users on the new version saw a blank home screen. Debug builds and tests were fine.
- Stack traces were unreadable names like
a.b.c. - Cause: R8 renamed fields of a data class that a reflection-based JSON library read by name. Parsing returned empty or null values.
- Reproduce it by installing the release variant locally (for example
./gradlew installPaidRelease, which needs a signing config, or set the debug key on a staging build type that has minify turned on). - Upload the mapping file (
app/build/outputs/mapping/<variant>/mapping.txt) to your crash tool, or useretrace, so traces become readable. - Add a keep rule for the model classes, or use annotations or code generation (for example Moshi or kotlinx.serialization codegen) that do not rely on field names at runtime.
- Run UI tests against a minified build in CI. Debug-only testing misses this class of bug.
- The analytics team saw fake purchases from internal testers mixed into production numbers.
- Cause: debug builds used the same
applicationIdand the same production analytics key as release. Every tester session on a debug build was counted as a real user.
- Give debug its own
applicationIdSuffixso it is a separate app that installs beside release and is easy to filter out. - Move per-environment values (API URL, analytics key) into
buildConfigFieldper build type or flavor. Read secrets from CI, not from Git. - Add a staging build type if QA needs release-like behavior with a test backend.
Common mistakes
- Confusing
compileSdkwithtargetSdk. One lets you call new APIs. The other opts you into new behavior rules. - Using
apieverywhere. It leaks dependencies to every consumer and slows incremental builds. Start withimplementation. - Testing only the debug variant. R8 and signing issues appear in release only.
- Hardcoding versions in each module. Versions drift apart. Use the version catalog.
- Committing keystore passwords. Anyone with repo access can sign as you. Use environment variables or a secrets store.
- Using
kaptfor new code. KSP is the supported, faster path for libraries that provide it.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between compileSdk, targetSdk and minSdk?”
“What is a build variant?”
“implementation or api?”
“A release build crashes but debug works. How do you investigate?”
Quiz
Which setting changes the runtime behavior rules your app opts into?
A build has flavors free and paid, and build types debug and release. How many variants are there?
You add libs.okhttp in build.gradle.kts. Where should the version be defined?
A model class parses fine in debug but returns empty fields in release. What is the most likely cause?
0 of 4 answered
Mini task
In any project, do this in 15 minutes:
- Add a
stagingbuild type withapplicationIdSuffix = ".staging"and abuildConfigFieldnamedAPI_URL. UseinitWith(getByName("debug"))or copy the settings you need. - Enable
buildConfig = trueand showBuildConfig.API_URLon a screen. - Install the debug and staging builds. Check that both apps appear on the device at the same time.
- Run
./gradlew :app:dependenciesand find one library that appears with a version you did not choose.
You are done when two installed apps show two different URLs and you can say which Gradle setting made them separate apps.