Gradle basics and build variants

How Gradle builds an Android app, how build types, flavors and version catalogs shape the result, and what usually goes wrong. About 25 minutes.

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 compileSdk vs targetSdk, implementation vs api, 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:

PhaseWhat happens
InitializationReads settings.gradle.kts and decides which modules exist
ConfigurationRuns each module's build file and builds the task graph
ExecutionRuns only the tasks needed, skipping those whose inputs did not change

The real names:

TermMeaning
Build typeHow it is built: debug, release, or your own such as staging
Product flavorWhat it is built for: free, paid, demo. Needs a flavorDimensions entry
Build variantOne flavor plus one build type, for example freeDebug
minSdkLowest Android version the app installs on
targetSdkThe Android version the app says it was tested on. It turns on that version's behavior changes
compileSdkThe API level you compile against. It controls which APIs you can call, not where the app runs

Notes

  • compileSdk is a compile-time choice. Raising it does not change runtime behavior. Raising targetSdk does, so test again.
  • namespace in build.gradle.kts sets the package for R and generated code. applicationId is 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 = true removes 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 the java-library plugin or an Android library module).
    • debugImplementation, testImplementation, androidTestImplementation: only for that variant or test set.
    • ksp(...): annotation processors that use KSP. Prefer KSP over kapt for Room, Hilt and Moshi codegen.
  • A version catalog (gradle/libs.versions.toml) has [versions], [libraries] and [plugins]. In build files you write libs.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

Crash only in release: the JSON fields were null
  • 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.
The fix
  1. 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).
  2. Upload the mapping file (app/build/outputs/mapping/<variant>/mapping.txt) to your crash tool, or use retrace, so traces become readable.
  3. 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.
  4. Run UI tests against a minified build in CI. Debug-only testing misses this class of bug.
QA test data appeared in production analytics
  • The analytics team saw fake purchases from internal testers mixed into production numbers.
  • Cause: debug builds used the same applicationId and the same production analytics key as release. Every tester session on a debug build was counted as a real user.
The fix
  • Give debug its own applicationIdSuffix so it is a separate app that installs beside release and is easy to filter out.
  • Move per-environment values (API URL, analytics key) into buildConfigField per 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 compileSdk with targetSdk. One lets you call new APIs. The other opts you into new behavior rules.
  • Using api everywhere. It leaks dependencies to every consumer and slows incremental builds. Start with implementation.
  • 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 kapt for 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:

  1. Add a staging build type with applicationIdSuffix = ".staging" and a buildConfigField named API_URL. Use initWith(getByName("debug")) or copy the settings you need.
  2. Enable buildConfig = true and show BuildConfig.API_URL on a screen.
  3. Install the debug and staging builds. Check that both apps appear on the device at the same time.
  4. Run ./gradlew :app:dependencies and 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.

Next: The manifest and app components