TExcelTAD
Home › Mobile Build Pipelines: Gradle/AGP, Xcode, SwiftPM & Fastlane › Mini Project: A CI-Ready Android Release

Mini Project: A CI-Ready Android Release

Time to put the Android half of the course together. You'll build the release pipeline for a small app, exactly as a CI job would run it, and prove the outputs are right before anything gets uploaded.

Requirements

# Requirement Lesson
1 Two product flavors, free and paid, installable side by side Product Flavors
2 versionName from the Git tag, versionCode derived from it plus a CI build number versionCode & versionName
3 Release signing from Gradle properties only: no secrets in the repository Signing Configs
4 R8 and resource shrinking on release, with a keep rule for the one reflective class R8, Keep Rules
5 Outputs: a signed release APK and an App Bundle for free App Bundles
6 A verification script that fails the job if the APK or bundle isn't right Verifying APKs
7 Gradle settings for CI: build cache, configuration cache Gradle Performance on CI

Step 1: the project

The app shows a price formatted by a flavor-specific Pricing class, loaded by name (a plugin-style design that needs a keep rule). The build script implements requirements 1 to 4 and 7:

kotlin
// app/build.gradle.kts
plugins { id("com.android.application") }

val gitVersion = providers.exec {
    commandLine("git", "describe", "--tags", "--abbrev=0", "--match", "v*")
    isIgnoreExitValue = true
}.standardOutput.asText.map { it.trim().removePrefix("v").ifEmpty { "0.0.0" } }
val buildNumber = providers.gradleProperty("buildNumber").map { it.toInt() }.orElse(0)

fun versionCodeOf(version: String, build: Int): Int {
    val (major, minor, patch) = version.split(".").map { it.toInt() }
    require(minor < 100 && patch < 100 && build < 100) { "version $version build $build out of range" }
    return (((major * 100 + minor) * 100 + patch) * 100 + build) * 10
}

android {
    namespace = "com.example.shop"
    compileSdk = 36
    defaultConfig {
        applicationId = "com.example.shop"
        minSdk = 24
        targetSdk = 36
        versionName = gitVersion.get()
        versionCode = versionCodeOf(gitVersion.get(), buildNumber.get()).coerceAtLeast(1)
    }
    signingConfigs {
        create("release") {
            val storePath = providers.gradleProperty("releaseStoreFile").orNull
            if (storePath != null) {
                storeFile = file(storePath)
                storePassword = providers.gradleProperty("releaseStorePassword").get()
                keyAlias = providers.gradleProperty("releaseKeyAlias").get()
                keyPassword = providers.gradleProperty("releaseKeyPassword").get()
            }
        }
    }
    buildTypes {
        release {
            isMinifyEnabled = true
            isShrinkResources = true
            proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
            signingConfig = signingConfigs.getByName("release")
        }
    }
    flavorDimensions += "tier"
    productFlavors {
        create("free") {
            dimension = "tier"
            applicationIdSuffix = ".free"
            buildConfigField("String", "PRICING", "\"com.example.shop.FreePricing\"")
        }
        create("paid") {
            dimension = "tier"
            buildConfigField("String", "PRICING", "\"com.example.shop.PaidPricing\"")
        }
    }
    buildFeatures { buildConfig = true }
    packaging { resources { excludes += "**/*.kotlin_builtins" } }
}

dependencies { testImplementation("junit:junit:4.13.2") }

Step 2: build and verify, as CI would

The session sets up the repository, tags v2.3.1, exports the signing properties the way a CI job maps its secrets, runs tests and the release build, and then runs ci/verify-release.sh. Read the script: it's requirement 6.

bash · try it yourself
mkdir -p shop/app/src/main/java/com/example/shop shop/app/src/test/java/com/example/shop shop/app/src/main/res/values shop/ci && cd shop
cat > settings.gradle.kts <<'KTS'
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
dependencyResolutionManagement {
    repositoriesMode = RepositoriesMode.FAIL_ON_PROJECT_REPOS
    repositories { google(); mavenCentral() }
}
rootProject.name = "shop"
include(":app")
KTS
echo 'plugins { id("com.android.application") version "9.4.1" apply false }' > build.gradle.kts
printf 'org.gradle.caching=true\norg.gradle.configuration-cache=true\n' > gradle.properties
printf '*.jks\n*.keystore\nlocal.properties\nbuild/\n.gradle/\n' > .gitignore
cat > app/build.gradle.kts <<'KTS'
plugins { id("com.android.application") }

val gitVersion = providers.exec {
    commandLine("git", "describe", "--tags", "--abbrev=0", "--match", "v*")
    isIgnoreExitValue = true
}.standardOutput.asText.map { it.trim().removePrefix("v").ifEmpty { "0.0.0" } }
val buildNumber = providers.gradleProperty("buildNumber").map { it.toInt() }.orElse(0)

fun versionCodeOf(version: String, build: Int): Int {
    val (major, minor, patch) = version.split(".").map { it.toInt() }
    require(minor < 100 && patch < 100 && build < 100) { "version $version build $build out of range" }
    return (((major * 100 + minor) * 100 + patch) * 100 + build) * 10
}

android {
    namespace = "com.example.shop"
    compileSdk = 36
    defaultConfig {
        applicationId = "com.example.shop"
        minSdk = 24
        targetSdk = 36
        versionName = gitVersion.get()
        versionCode = versionCodeOf(gitVersion.get(), buildNumber.get()).coerceAtLeast(1)
    }
    signingConfigs {
        create("release") {
            val storePath = providers.gradleProperty("releaseStoreFile").orNull
            if (storePath != null) {
                storeFile = file(storePath)
                storePassword = providers.gradleProperty("releaseStorePassword").get()
                keyAlias = providers.gradleProperty("releaseKeyAlias").get()
                keyPassword = providers.gradleProperty("releaseKeyPassword").get()
            }
        }
    }
    buildTypes {
        release {
            isMinifyEnabled = true
            isShrinkResources = true
            proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
            signingConfig = signingConfigs.getByName("release")
        }
    }
    flavorDimensions += "tier"
    productFlavors {
        create("free") {
            dimension = "tier"
            applicationIdSuffix = ".free"
            buildConfigField("String", "PRICING", "\"com.example.shop.FreePricing\"")
        }
        create("paid") {
            dimension = "tier"
            buildConfigField("String", "PRICING", "\"com.example.shop.PaidPricing\"")
        }
    }
    buildFeatures { buildConfig = true }
    packaging { resources { excludes += "**/*.kotlin_builtins" } }
}

dependencies { testImplementation("junit:junit:4.13.2") }
KTS
cat > app/proguard-rules.pro <<'PRO'
# Pricing implementations are loaded by name from BuildConfig.PRICING
-keep class * implements com.example.shop.Pricing { <init>(); }
PRO
cat > app/src/main/AndroidManifest.xml <<'XML'
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:label="@string/app_name">
        <activity android:name=".MainActivity" android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
XML
cat > app/src/main/res/values/strings.xml <<'XML'
<resources>
    <string name="app_name">Shop</string>
    <string name="legacy_banner">Old banner nobody shows</string>
</resources>
XML
cat > app/src/main/java/com/example/shop/Pricing.java <<'JAVA'
package com.example.shop;

public interface Pricing { int priceCents(int baseCents); }
JAVA
cat > app/src/main/java/com/example/shop/FreePricing.java <<'JAVA'
package com.example.shop;

public class FreePricing implements Pricing { public int priceCents(int base) { return base; } }
JAVA
cat > app/src/main/java/com/example/shop/PaidPricing.java <<'JAVA'
package com.example.shop;

public class PaidPricing implements Pricing { public int priceCents(int base) { return base * 80 / 100; } }
JAVA
cat > app/src/main/java/com/example/shop/MainActivity.java <<'JAVA'
package com.example.shop;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
    static Pricing pricing() throws Exception {
        return (Pricing) Class.forName(BuildConfig.PRICING).getDeclaredConstructor().newInstance();
    }

    @Override protected void onCreate(Bundle state) {
        super.onCreate(state);
        String text;
        try { text = getString(R.string.app_name) + ": " + pricing().priceCents(1000) + " cents"; }
        catch (Exception e) { text = e.toString(); }
        TextView view = new TextView(this);
        view.setText(text);
        setContentView(view);
    }
}
JAVA
cat > app/src/test/java/com/example/shop/PricingTest.java <<'JAVA'
package com.example.shop;

import static org.junit.Assert.assertEquals;
import org.junit.Test;

public class PricingTest {
    @Test public void paidGetsTwentyPercentOff() { assertEquals(800, new PaidPricing().priceCents(1000)); }
    @Test public void freePaysFullPrice() { assertEquals(1000, new FreePricing().priceCents(1000)); }
}
JAVA
cat > ci/verify-release.sh <<'SH'
#!/bin/bash
# Usage: ci/verify-release.sh APK AAB EXPECTED_VERSION_CODE EXPECTED_SIGNER_DN
set -euo pipefail
APK=$1 AAB=$2 CODE=$3 DN=$4
fail() { echo "FAIL: $*"; exit 1; }
zipalign -c -P 16 4 "$APK"                                   || fail "APK is not aligned"
apksigner verify --print-certs "$APK" > signer.txt           || fail "APK signature does not verify"
grep -q "certificate DN: $DN" signer.txt                     || fail "APK signed by $(grep -o 'DN: .*' signer.txt)"
badging=$(aapt2 dump badging "$APK")
grep -q "versionCode='$CODE'" <<< "$badging"                 || fail "versionCode is not $CODE"
! grep -q application-debuggable <<< "$badging"              || fail "APK is debuggable"
perms=$(aapt2 dump permissions "$APK" | grep -c uses-permission)
[ "$perms" -eq 1 ]                                           || fail "expected 1 permission, found $perms"
keytool -printcert -jarfile "$AAB" | grep -q "Owner: $DN"    || fail "bundle signed by someone else"
bundletool validate --bundle="$AAB" > /dev/null              || fail "bundle is invalid"
bundletool build-apks --bundle="$AAB" --output=check.apks --mode=universal \
  --ks="$ORG_GRADLE_PROJECT_releaseStoreFile" --ks-key-alias="$ORG_GRADLE_PROJECT_releaseKeyAlias" \
  --ks-pass="pass:$ORG_GRADLE_PROJECT_releaseStorePassword" --key-pass="pass:$ORG_GRADLE_PROJECT_releaseKeyPassword"
echo "OK: $(basename "$APK") and $(basename "$AAB"), versionCode $CODE, signed by $DN"
SH
chmod +x ci/verify-release.sh
git init -q && git add -A && git commit -q -m "Shop 2.3.1" && git tag v2.3.1
gradle wrapper > /dev/null

# --- what the CI job does from here on ---
export ORG_GRADLE_PROJECT_releaseStoreFile=$HOME/release.jks ORG_GRADLE_PROJECT_releaseKeyAlias=release
export ORG_GRADLE_PROJECT_releaseStorePassword=learner-pass ORG_GRADLE_PROJECT_releaseKeyPassword=learner-pass
./gradlew test assembleFreeRelease bundleFreeRelease -PbuildNumber=14 | grep -E 'Task :app:(test.*UnitTest|minify.*|sign.*|package.*Release)$|^BUILD|actionable'
APK=app/build/outputs/apk/free/release/app-free-release.apk
AAB=app/build/outputs/bundle/freeRelease/app-free-release.aab
ci/verify-release.sh $APK $AAB 20301140 "CN=Ada Lovelace, O=Example, C=GB"
echo "--- what shipped"
aapt2 dump badging $APK | head -1 | cut -d' ' -f2-4
grep -E '^com.example' app/build/outputs/mapping/freeRelease/mapping.txt
aapt2 dump resources $APK | grep -o 'string/[a-z_]*'
bundletool get-size total --apks=check.apks | tr -d '\r'    # bundletool ends these lines with CRLF
> Task :app:testFreeDebugUnitTest
> Task :app:testPaidDebugUnitTest
> Task :app:minifyFreeReleaseWithR8
> Task :app:packageFreeRelease
> Task :app:signFreeReleaseBundle
BUILD SUCCESSFUL in 17s
97 actionable tasks: 83 executed, 14 from cache
OK: app-free-release.apk and app-free-release.aab, versionCode 20301140, signed by CN=Ada Lovelace, O=Example, C=GB
--- what shipped
name='com.example.shop.free' versionCode='20301140' versionName='2.3.1'
com.example.shop.FreePricing -> com.example.shop.FreePricing:
com.example.shop.MainActivity -> com.example.shop.MainActivity:
com.example.shop.PaidPricing -> com.example.shop.PaidPricing:
com.example.shop.Pricing -> a:
string/app_name
MIN,MAX
4393,4393

Every requirement is visible in the output: both flavors' unit tests ran, R8 shrank the free release and kept both Pricing implementations and the activity under their real names, while the interface itself was renamed to a, the unused legacy_banner string is gone, the version is 2.3.1 with code 20301140 (tag 2.3.1, build 14), and the verification script passed every check on both artifacts.

Step 3: break it on purpose

A verification script you've never seen fail isn't trustworthy. Try these one at a time in your copy of the session and confirm the job goes red with a clear message:

Change Expected failure
unset ORG_GRADLE_PROJECT_releaseStoreFile Gradle: Keystore file not set for signing config release
sign with the debug key (signingConfig = signingConfigs.getByName("debug")) FAIL: APK signed by DN: C=US, O=Android, CN=Android Debug
-PbuildNumber=15 but expect 20301140 FAIL: versionCode is not 20301140
add <uses-permission android:name="android.permission.CAMERA" /> FAIL: expected 1 permission, found 2
remove the keep rule the build passes (!); only a runtime test of the release APK catches it: add an instrumented smoke test on a minified build to your nightly job

The last row is the honest limit of static checks, and the reason Field Notes insist on testing minified builds.

Step 4: wire it into CI

Drop the session's commands into the release job from GitHub Actions for Android Releases: the secrets become the four ORG_GRADLE_PROJECT_* variables, -PbuildNumber=${{ github.run_number }} replaces 14, the expected version code is computed by the same formula in a step before the build, and the upload is a Fastlane lane (Fastlane for Android) that runs only after ci/verify-release.sh has passed. Then continue with Part 2: the iOS equivalent.

Test yourself

Why does the verify script check the signer's DN (or digest) instead of only apksigner verify?

  1. apksigner verify doesn't check signatures
  2. A valid signature from the wrong key (e.g. the debug key) still verifies
  3. DN checks are faster
  4. Play requires the DN

Removing the keep rule doesn't fail the verification. What would catch it?

  1. zipalign -c
  2. A runtime test (instrumented smoke test) of the minified release build
  3. bundletool validate
  4. aapt2 dump badging

Which inputs determine the versionCode 20301140 in the session?

  1. The current time
  2. The Git tag v2.3.1 and the CI build number 14
  3. The keystore
  4. The number of commits