Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 104 ยท Shipping to Users

CI/CD for Android

Automate Android builds with GitHub Actions: Gradle caching, lint and unit tests on every pull request, signed release bundles, internal-track uploads and automatic versioning.

Building and releasing an app by hand works for the first few versions. Then someone forgets to run the tests, someone else ships a bundle built from the wrong branch, and a release takes an afternoon because only one laptop has the signing key. Continuous integration (CI) fixes the first half of that: every change is built and tested automatically on a clean machine. Continuous delivery (CD) fixes the second half: a tagged version is signed, uploaded and ready for testers without anyone clicking through menus.

This lesson uses GitHub Actions because it is popular and free for public repositories, but the ideas are the same on GitLab CI, Bitrise, Jenkins or any other system. A CI job is a fresh Linux machine that runs a list of steps. The real workflow files and Gradle config in this lesson are read-only, because the site cannot start a pipeline. The TryIts are plain Kotlin stand-ins on Piston: a stage runner that skips work after a failure, a cache-key model and a version-number calculator. They show the logic that GitHub Actions and Gradle implement for you. You should already know Gradle for Android and signing release builds.

What a good pipeline does

Think of two pipelines with different jobs.

  • Pull request pipeline. Runs on every push to a pull request. It must be fast (aim for under ten minutes) and it answers one question: "is this change safe to merge?" It runs lint, unit tests and a debug build.
  • Release pipeline. Runs when you push a version tag such as v1.4.0. It runs the same checks again, builds a signed App Bundle, and uploads it to the Play internal testing track. Promotion to production stays a deliberate step in the Play Console.
flowchart LR
    A["Push or pull request"] --> B["Checkout"]
    B --> C["Lint"]
    B --> D["Unit tests"]
    C --> E["Build debug APK"]
    D --> E
    F["Push tag v1.4.0"] --> G["Checks pass"]
    G --> H["Build signed bundle"]
    H --> I["Upload to internal track"]

Lint and unit tests run side by side. A tag adds the signing and upload stages after the same checks.

Notice that lint and tests do not depend on each other, so they can run in parallel (as separate jobs) and the pipeline takes as long as the slower one, not the sum.

A pull request workflow

GitHub reads workflows from .github/workflows/*.yml. This one runs on pull requests and on pushes to main.

YAML
# .github/workflows/ci.yml  (read-only)
name: CI

on:
  pull_request:
  push:
    branches: [main]

concurrency:
  group: ci-${{ github.ref }}
  cancel-in-progress: true

jobs:
  check:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: 21

      - uses: gradle/actions/setup-gradle@v4

      - name: Lint
        run: ./gradlew lintDebug

      - name: Unit tests
        run: ./gradlew testDebugUnitTest

      - name: Build debug APK
        run: ./gradlew assembleDebug

      - name: Keep reports when something fails
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: reports
          path: |
            **/build/reports/
            **/build/test-results/

A few details deserve attention:

  • concurrency with cancel-in-progress stops an older run when you push a new commit to the same branch. You never wait for results about code that is already outdated.
  • timeout-minutes keeps a hung emulator or Gradle daemon from burning your free minutes for six hours.
  • ./gradlew is the Gradle wrapper checked into the repo, so CI uses the exact Gradle version you do. Never rely on a Gradle installed on the runner.
  • if: failure() uploads the HTML lint and test reports only when something broke, so you can read them from the run page.
  • The JDK is the one Gradle itself needs. Check the Android Gradle Plugin documentation for the minimum version your plugin requires.

The wrapper file also needs to be executable in git. If you see Permission denied on ./gradlew, run git update-index --chmod=+x gradlew once and commit.

Run the pipeline logic yourself

A pipeline is a set of stages with dependencies. If a stage fails, every stage that needs it is skipped, but independent stages still run. The wall-clock time is not the sum of all stages, it is the length of the longest chain. The stand-in below models that. It is not GitHub Actions, but it applies the same rule: a stage starts when everything it needs has finished.

Kotlin A pipeline stage runner (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In run 1, lint and unit tests start at the same moment (right after checkout), so the 40-second lint hides inside the 90-second test stage. The work adds up to 200 seconds but the wall clock is 160. In run 2 the failing test makes assemble-debug and upload-reports skip, but lint still ran and reported its own result. That is what you want from CI: one failure should not hide other findings.

Caching Gradle

A clean runner has nothing: no Gradle distribution, no downloaded libraries, no build outputs. Downloading and compiling everything on each run can easily take most of the pipeline time. The gradle/actions/setup-gradle step manages the cache for you. It restores ~/.gradle/caches and the wrapper distribution, and saves them when the job ends. It also publishes a build scan summary on request, which helps find slow tasks.

Two rules keep caches useful:

  1. The cache key must change when dependencies change. The action derives the key from your Gradle files (build scripts, gradle-wrapper.properties, version catalog). A new library version means a new key, and a cold start for that run.
  2. Write the cache from main, read it everywhere. Pull request runs restore the cache from main but do not overwrite it, so a pull request with experimental dependencies cannot poison the cache for everyone.

The next TryIt is a simplified cache that makes those two rules visible. The key is a hash of the build files, and the build takes less time on a hit.

Kotlin A Gradle cache key model (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Pull request B pays the full price twice because it is not allowed to save the cache. After the merge, main saves the new key, and pull request C is fast again. If that bothers you for a busy repository, a scheduled job on main can refresh the cache every night.

Gradle also has a build cache that reuses the outputs of individual tasks (a compiled module that did not change). Enable org.gradle.caching=true in gradle.properties and CI benefits too. Combine it with a multi-module project and a change in one module rebuilds only that module.

Tests and lint in CI

CI is only as good as the checks it runs. Three commands cover most projects:

  • ./gradlew testDebugUnitTest runs local JVM tests (your ViewModels, repositories and mappers). They are fast and need no device.
  • ./gradlew lintDebug runs Android Lint. Fail the build on new warnings by committing a lint baseline (lint { baseline = file("lint-baseline.xml") }) so old problems are accepted and only new ones break the build.
  • ./gradlew connectedDebugAndroidTest runs instrumented tests, but it needs an emulator or a device. On GitHub you can start an emulator with a community action, but those runs are slow and sometimes flaky. A common compromise is to run them nightly or only before a release, and to use a cloud device farm for wide coverage (see Instrumented, Room and Navigation Tests).

Keep the fast checks as required status checks on the main branch, so a pull request cannot be merged while they are red.

Versioning automatically

Each upload to Google Play needs a versionCode that is higher than any previous one. Humans forget; CI does not. A reliable scheme derives both numbers from the repository:

  • versionName is for people: 1.4.0. Take it from the git tag.
  • versionCode is for Play: an integer that only grows. Two common sources are the CI run number (simple, but it resets if you change systems) or a number computed from the semantic version.

A formula such as major * 1_000_000 + minor * 10_000 + patch * 100 + build gives readable codes (1.4.0 build 7 becomes 1,040,007) and always grows with the version. The maximum versionCode Play accepts is 2,100,000,000, so leave room.

Kotlin Version name and code from a tag (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Watch the v1.10.0 line: tagged after v2.0.0 (say, a fix for the old 1.x line), it gets a lower code and Play would reject it. Releasing from an older line needs its own rule, such as a higher build number or a separate track. The last line shows why you compare versions as numbers: as text, 1.10.0 sorts before 1.4.0. Reading the tag in Gradle looks like this:

Kotlin
// app/build.gradle.kts  (read-only)
val tag = providers.environmentVariable("GITHUB_REF_NAME").orNull
val buildNumber = providers.environmentVariable("GITHUB_RUN_NUMBER").orNull?.toInt() ?: 0

android {
    defaultConfig {
        versionName = tag?.removePrefix("v") ?: "0.0.0-dev"
        versionCode = 1_000_000 + buildNumber        // replace with your own formula
    }
}

Locally, GITHUB_REF_NAME is not set, so you get a harmless development version. Keep the logic in one place (the build script or a small convention plugin) so you never edit numbers by hand.

A release workflow

The release pipeline runs on tags. It needs three secrets from the repository settings: the keystore (as base64 text), its passwords and the alias, and a Google Play service account key. Secrets are masked in logs, but never print them yourself and never pass them to pull requests from forks (GitHub does not expose them there for good reason).

YAML
# .github/workflows/release.yml  (read-only)
name: Release

on:
  push:
    tags: ['v*']

jobs:
  release:
    runs-on: ubuntu-latest
    environment: production        # optional: requires approval before secrets are used
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: 21
      - uses: gradle/actions/setup-gradle@v4

      - name: Run the checks again
        run: ./gradlew lintRelease testReleaseUnitTest

      - name: Restore the keystore
        run: echo "$KEYSTORE_BASE64" | base64 --decode > "$RUNNER_TEMP/release.jks"
        env:
          KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}

      - name: Build the signed bundle
        run: ./gradlew bundleRelease
        env:
          KEYSTORE_PATH: ${{ runner.temp }}/release.jks
          KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
          KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
          KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}

      - name: Keep the bundle and the R8 mapping file
        uses: actions/upload-artifact@v4
        with:
          name: release-files
          path: |
            app/build/outputs/bundle/release/*.aab
            app/build/outputs/mapping/release/mapping.txt

      - name: Upload to the internal track
        run: ./gradlew publishReleaseBundle --track internal
        env:
          ANDROID_PUBLISHER_CREDENTIALS: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }}

The upload step assumes the Gradle Play Publisher plugin (com.github.triplet.play) is applied in app/build.gradle.kts; it reads the service account JSON from the ANDROID_PUBLISHER_CREDENTIALS environment variable. Other tools such as Fastlane or a dedicated GitHub Action do the same job with different syntax. In your signingConfigs block, read the keystore details from the same environment variables, as shown in the signing lesson.

Notes on safety and traceability:

  • The keystore is written to RUNNER_TEMP, which is deleted with the machine, never into the repository.
  • The .aab and mapping.txt are saved as build artifacts, so a crash report from this exact release can be de-obfuscated later. The Play upload also takes the mapping file for crash reports.
  • The environment: production line lets you require a human approval in GitHub before this job gets the secrets.
  • Uploading to internal testing is safe: only your listed testers get the build, and you promote it through closed and open tracks to production from the Console with a staged rollout.

Common mistakes

  • Committing the keystore or a local.properties with passwords. Use CI secrets and environment variables.
  • A cache key that never changes, so stale dependencies stick around, or one that always changes, so the cache never hits.
  • Running emulator tests on every push and teaching the team to ignore the flaky red results.
  • Forgetting cancel-in-progress, so five commits mean five full pipelines.
  • Setting versionCode by hand and getting "Version code 12 has already been used" at upload time.
  • Letting pull requests from forks run with release secrets.
  • Not storing mapping.txt, which makes production stack traces unreadable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can lint and unit tests run as separate parallel jobs in a pipeline?

    Independent stages can start at the same time. Only stages that depend on earlier results, like assembling the app, must wait.
  2. 2. When should the Gradle dependency cache be written?

    Writing from main keeps one trusted cache. If every pull request could overwrite it, an experimental dependency change could slow down or break unrelated runs.
  3. 3. What is true about versionCode for Google Play uploads?

    versionName is the human-readable label. Play compares versionCode as an integer and rejects an upload that is not higher than the previous ones.
  4. 4. Why does the release workflow save mapping.txt as an artifact?

    R8 renames classes and methods in release builds. The mapping file for that build is the only way to turn the obfuscated names in crash reports back into readable ones.
  5. 5. Where should the release keystore and its passwords live in a CI setup?

    Secrets stay out of version control. CI decodes the keystore into a temporary location that disappears with the runner, and passes passwords through environment variables.

Summary

  • CI builds and tests every change on a clean machine; CD turns a tagged commit into a signed bundle on a testing track.
  • A pull request pipeline runs lint, unit tests and a debug build quickly; slower device tests run nightly or before releases.
  • Stages with dependencies run in parallel when they can, and a failed stage skips only the stages that need it.
  • Use the Gradle wrapper, setup-gradle caching (written from main, restored everywhere) and cancel-in-progress to keep runs fast and cheap.
  • Derive versionName from the git tag and compute a growing versionCode; never edit them by hand.
  • Keep keystores and Play credentials in CI secrets, store mapping.txt with every release, and upload to the internal track first.
  • The YAML and Gradle files are read-only; the TryIts are Kotlin stand-ins for the stage, cache and versioning logic.

Next: Project: Notes App