Skip to content
Tutorials Center
My learning

Topics

Lesson 88 of 104 ยท Shipping to Users

Signing and Release Builds

Sign and ship an Android app: keystores, Play App Signing, App Bundles versus APKs, R8 mapping files, build variants, versionCode rules and safe secrets handling.

Everything you have built so far runs as a debug build, signed automatically with a throwaway key that Android Studio created on your machine. A release is different. You must sign the app with a key you control and keep for the entire life of the app, you must produce the file format the store expects, you must raise the version number every time, and you must keep a few files safe so you can read crash reports later. A mistake with the signing key can be impossible to undo, so this is worth understanding properly before the day you ship.

This lesson covers keystores and signing, Play App Signing, Android App Bundles versus APKs, the R8 mapping file, build variants, versionCode and versionName, and secrets handling during builds. It builds on Gradle for Android, Performance and Profiling (for R8) and Securing Your App. Signing and packaging need the Android Gradle Plugin and a real keystore, so the commands and configuration are read-only. The TryIt blocks are plain-Kotlin stand-ins that model the arithmetic of version codes and the matrix of build variants, which is where most release mistakes happen.

Why apps are signed

Every Android package must carry a digital signature before it can be installed. The signature does two jobs:

  • Identity. The certificate in the signature identifies the author. An update is accepted only if it is signed with the same key as the installed version, so nobody else can push a malicious "update" to your users.
  • Integrity. The signature covers the contents of the package, so any change after signing makes verification fail.

Android also uses the signing certificate for permissions with protectionLevel="signature", for sharing a process or user id between your own apps, and for verified App Links (the certificate fingerprint goes into assetlinks.json, see Back Stack, Launch Modes and Deep Links).

The consequence is the rule to remember: the signing key is the app's identity. If you lose it, you cannot update the app under the same identity. For apps on Google Play, Play App Signing (below) removes most of that risk.

Keystores and keys

A keystore is a file (.jks or .p12) that holds one or more private keys with their certificates, protected by passwords. You create one with the keytool program that ships with the JDK, or from Android Studio under Build, Generate Signed App Bundle:

Terminal
# read-only example: creating an upload keystore
keytool -genkeypair -v \
  -keystore upload-keystore.jks \
  -alias upload \
  -keyalg RSA -keysize 4096 \
  -validity 10000

keytool asks for the passwords and for a name and organization. The -validity is in days; use a long period (Google recommends validity until at least 2033 or beyond), because the certificate's expiry can matter for old installs. Then inspect it:

Terminal
# read-only example: listing a key's certificate fingerprints
keytool -list -v -keystore upload-keystore.jks -alias upload

The output includes SHA-1 and SHA-256 fingerprints, which are what services such as Firebase, Google Sign-In and App Links ask you for. Treat the keystore like a password: do not commit it to git, do not email it, keep at least two encrypted backups in different places, and store the passwords in a password manager.

Play App Signing

For apps in Google Play, you normally enroll in Play App Signing (required for new apps that use App Bundles). The model has two keys:

  • The app signing key is held by Google. Play uses it to sign the APKs that users actually install.
  • The upload key is yours. You sign the bundle you upload with it, so Google knows the upload came from you.
flowchart LR
    A["Your build<br/>signed with the upload key"] --> B["Google Play<br/>verifies upload key"]
    B --> C["Play re-signs with the<br/>app signing key"]
    C --> D["Users install APKs<br/>signed by the app signing key"]

You sign with an upload key; Google re-signs with the app signing key that users see.

The benefit is safety: if you lose or leak the upload key, you can ask Google to reset it, and your users keep receiving updates because the app signing key never changed. Without Play App Signing, losing your only key would mean you could never update the existing app. The trade-off is that services that need the certificate fingerprint (App Links, some APIs) must use the fingerprint from the Play Console's App signing page, not the fingerprint of your upload key.

Configuring signing in Gradle

The Android Gradle Plugin signs the release build for you if you describe the key. The configuration must read the passwords from outside your repository:

Kotlin
// read-only example: app/build.gradle.kts
import java.util.Properties

val keystoreProps = Properties().apply {
    val file = rootProject.file("keystore.properties")   // listed in .gitignore
    if (file.exists()) file.inputStream().use { load(it) }
}

android {
    signingConfigs {
        create("release") {
            val path = System.getenv("UPLOAD_KEYSTORE_PATH") ?: keystoreProps.getProperty("storeFile")
            if (path != null) {
                storeFile = file(path)
                storePassword = System.getenv("UPLOAD_STORE_PASSWORD") ?: keystoreProps.getProperty("storePassword")
                keyAlias = System.getenv("UPLOAD_KEY_ALIAS") ?: keystoreProps.getProperty("keyAlias")
                keyPassword = System.getenv("UPLOAD_KEY_PASSWORD") ?: keystoreProps.getProperty("keyPassword")
            }
        }
    }

    buildTypes {
        release {
            isMinifyEnabled = true
            isShrinkResources = true
            proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
            signingConfig = signingConfigs.getByName("release")
        }
    }
}

On your laptop the values come from a git-ignored keystore.properties; on a CI server they come from environment variables that the CI system stores as encrypted secrets (see CI/CD for Android). The same build file works in both places, and the secrets never appear in version control.

APK versus App Bundle

There are two package formats you will hear about:

  • An APK (Android Package) is the file a device installs. One APK contains the code, resources and native libraries for every screen density, language and CPU architecture you support, so it is bigger than any single device needs.
  • An AAB (Android App Bundle) is a publishing format, not an installable file. You upload it to Google Play, which then generates optimized APKs for each device: only the right density resources, the right languages and the right CPU libraries. Users download smaller apps, typically noticeably smaller than a universal APK.

Google Play requires an AAB for new apps. You build each one with a Gradle task:

Terminal
# read-only example: building release artifacts
./gradlew bundleRelease     # app/build/outputs/bundle/release/app-release.aab
./gradlew assembleRelease   # app/build/outputs/apk/release/app-release.apk

Use the AAB for Play, and an APK when you want to install a release build directly (for testing it on a device, or distributing outside Play). You can test what Play would deliver from a bundle with Google's bundletool, which builds device-specific APKs and installs them:

Terminal
# read-only example: bundletool
bundletool build-apks --bundle=app-release.aab --output=app.apks --connected-device
bundletool install-apks --apks=app.apks

Android also has several APK signature schemes. v1 is the old JAR signing, v2 and v3 sign the whole file (v3 supports key rotation), and v4 supports incremental installs. The Android Gradle Plugin picks the right ones for your minSdk, and you check the result with apksigner verify --verbose app-release.apk.

The R8 mapping file and native symbols

In Performance and Profiling you learned that R8 renames classes and methods in release builds. A crash stack trace from a user then reads at a.b.c.d(SourceFile:12), which is useless. The build writes a mapping file at app/build/outputs/mapping/release/mapping.txt that translates the short names back. Without the mapping for the exact build that is in users' hands, you cannot read its crashes.

  • When you upload an AAB, Google Play extracts the mapping file bundled in it and deobfuscates crashes in the Play Console automatically. For an APK distributed elsewhere, upload the file to your crash-reporting service yourself (Firebase Crashlytics has a Gradle plugin that does it).
  • Keep a copy of mapping.txt for every release you ship, named by version, in your CI artifacts. Each build produces a different mapping, so an old one does not decode a new crash.
  • If your app contains native libraries, include native debug symbols (ndk { debugSymbolLevel = "SYMBOL_TABLE" }, or FULL) so native crashes can be symbolicated as well.

You decode a trace manually with the retrace tool from the command-line tools: retrace mapping.txt stacktrace.txt.

Build types, flavors and variants

You already know the two default build types, debug and release. A product flavor is a second axis: a different version of the app built from the same code, such as free and paid, or staging and production. Every combination of flavor and build type is a build variant.

Kotlin
// read-only example: app/build.gradle.kts
android {
    flavorDimensions += listOf("tier", "env")

    productFlavors {
        create("free")       { dimension = "tier" }
        create("paid")       { dimension = "tier"; applicationIdSuffix = ".pro" }
        create("staging")    { dimension = "env"; applicationIdSuffix = ".staging"
                               buildConfigField("String", "API_URL", "\"https://staging.example.com/\"") }
        create("production") { dimension = "env"
                               buildConfigField("String", "API_URL", "\"https://api.example.com/\"") }
    }

    buildTypes {
        debug   { applicationIdSuffix = ".debug" }
        release { isMinifyEnabled = true }
    }
}

Variant names are built from the flavor names (in the order of the dimensions) followed by the build type, joined in camelCase: freeStagingDebug, paidProductionRelease. Gradle creates tasks and source folders for every variant, for example assembleFreeStagingDebug and src/freeStagingDebug/. Each flavor can have its own source set (src/paid/), resources (a different app name and icon) and dependencies (paidImplementation(...)). Giving staging and debug builds a different application id suffix lets you install them next to the production app on the same phone.

More dimensions multiply the variants: two tiers times two environments times two build types is eight, and three dimensions of three options is already 54. Keep the matrix small, and use variant filtering to remove combinations you never build. Prefer runtime configuration (a remote config flag, a settings screen in debug builds) over a flavor when the difference is only data.

The variant matrix, modeled

This stand-in generates the variant names from a list of dimensions and a list of build types, applies an application-id suffix rule and filters out variants you do not need. It is plain Kotlin and mirrors how Gradle names variants, so you can predict the tasks your configuration will create.

Kotlin Build variant matrix (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.

Notice that the application id of freeStagingDebug ends in .staging.debug, so it installs beside paidProductionRelease, whose id has only .pro. Removing the staging release variants cut two of eight combinations.

versionCode and versionName

Every build carries two version values:

  • versionName is the string users see ("2.4.1"). It is for humans and can be any text.
  • versionCode is an integer the system and Google Play use to order releases. It must increase with every upload and never be reused; Play rejects an upload whose code was already used, even on another track. The maximum value is 2,100,000,000.

Updates only install over an older version when the new versionCode is higher, so a smaller number can never replace a larger one. A convenient scheme derives the code from the semantic version, leaving room for patch releases, or from your CI build number:

Kotlin
// read-only example: deriving the version from one place
val major = 2
val minor = 4
val patch = 1

android {
    defaultConfig {
        versionName = "$major.$minor.$patch"
        versionCode = major * 1_000_000 + minor * 10_000 + patch * 100
    }
}

The two spare digits at the end let you publish a hotfix of the same release (a rebuild with the same version name) as ...01 without renumbering. When you build split APKs per ABI outside Play, a common trick is to add an offset per architecture so each split has a distinct code (for example 1 for armeabi-v7a and 2 for arm64-v8a at the end of the number); with an AAB, Play handles the splitting and you do not need that.

Version code arithmetic

This stand-in computes version codes from a semantic version, checks that a list of releases is strictly increasing, and shows the overflow limit. The scheme is an example, not an Android requirement; Android only demands that the integer increases.

Kotlin Version code scheme and monotonic check (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.

The hotfix rebuild gets a higher code (1010001) than 1.1.0 (1010000) while keeping the same visible name, and the out-of-order 1.2.0 fails the check. If you use a CI counter as the version code instead, you never hit this class of mistake.

Secrets handling for release builds

Release builds need secrets: the keystore, its passwords, API keys for the build, and the service account that publishes to Play. A short policy keeps them safe:

  • Never commit keystores, keystore.properties, google-services.json with private data, or service account JSON. Add them to .gitignore before the first commit; removing a secret from git history later is painful and the secret must then be treated as leaked anyway.
  • Keep secrets in the CI secret store and pass them as environment variables; store the keystore itself as a base64 secret that the pipeline decodes into a temporary file.
  • Remember what ships. Values injected into BuildConfig or strings.xml are readable inside the final APK, so only put values there that are safe to be public (see Securing Your App).
  • Use different keys for debug and release and different backend credentials for staging and production.
  • Limit who can publish. Use a dedicated service account with the minimum Play Console permissions for automated uploads.

A release checklist

  1. Version code increased, version name updated.
  2. Release build type: debuggable false, R8 on, signing config set from environment values.
  3. Test the release build (or the AAB through bundletool) on a real device; R8 bugs only show there.
  4. Build the AAB; archive it with mapping.txt and native symbols as CI artifacts.
  5. Upload to an internal or closed testing track first (see Publishing on Google Play).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must an app update be signed with the same key as the installed version?

    The certificate is the app's identity. A package signed with a different key is rejected as an update, which stops anyone else from replacing your app.
  2. 2. With Play App Signing, which key do you keep and use for your builds?

    You sign uploads with the upload key; Google holds the app signing key and re-signs the APKs that users install. A lost upload key can be reset.
  3. 3. What is the main advantage of uploading an Android App Bundle instead of a universal APK?

    An AAB is a publishing format. Play generates optimized APKs containing only the resources, languages and CPU libraries a device needs.
  4. 4. Your release build has product flavors free and paid in one dimension and the usual debug and release build types. How many build variants does it have?

    Each flavor combines with each build type: 2 flavors times 2 build types gives 4 variants, such as freeDebug and paidRelease.
  5. 5. A crash report from production shows names like a.b.c. What do you need to read it?

    R8 renames code differently in each build. The mapping file for that exact build translates the short names back to your real classes and methods.

Summary

  • A signature proves identity and integrity; updates must be signed with the same key as the installed app, so the key is the app's identity.
  • Create keystores with keytool, guard them like passwords, keep encrypted backups, and read their passwords from git-ignored files or CI secrets.
  • Play App Signing splits the roles: you hold an upload key, Google holds the app signing key and re-signs what users install.
  • Publish an AAB to Play (smaller device-specific APKs); use APKs for direct installs; test with bundletool and verify with apksigner.
  • Keep mapping.txt and native symbols for every release so crashes can be decoded.
  • Variants are flavors times build types; keep the matrix small, use application id suffixes for side-by-side installs and filter combinations you never build.
  • versionCode must increase with every upload (maximum 2.1 billion); versionName is only for people.
  • Keep secrets out of git and the APK; test the release build before every upload.
  • Signing and packaging are read-only here; the TryIts model the variant matrix and the version code arithmetic.

Next: Publishing on Google Play