TExcelTAD

Mobile Build Exercises

Each exercise is a small piece of the logic a mobile release pipeline runs, written as a pure function with the tests already in place. Run the starter first: it prints wrong answers (None, empty lists), which shows what the tests expect. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last exercise is a real Gradle session to fix.

Exercise 1: Variant names

Topics: Product Flavors & Build Variants

Given the flavor dimensions (in priority order) and the build types, return every variant name in AGP's order and spelling: flavors in dimension order, then the build type, camel-cased (freePlayDebug).

python · try it yourself
def variant_names(dimensions, build_types):
    # TODO: cartesian product of the dimensions' flavors, then each build type; camelCase the parts
    return []

print(variant_names([["free", "paid"]], ["debug", "release"]))
print(variant_names([["free", "paid"], ["play", "galaxy"]], ["release"]))
print(len(variant_names([["a", "b"], ["c", "d", "e"], ["f", "g", "h"]], ["debug", "release"])))
[]
[]
0

Expected output:

text
['freeDebug', 'freeRelease', 'paidDebug', 'paidRelease']
['freePlayRelease', 'freeGalaxyRelease', 'paidPlayRelease', 'paidGalaxyRelease']
36
Show solution
python
from itertools import product

def variant_names(dimensions, build_types):
    names = []
    for combo in product(*dimensions):
        for bt in build_types:
            parts = list(combo) + [bt]
            names.append(parts[0] + "".join(p[:1].upper() + p[1:] for p in parts[1:]))
    return names

Exercise 2: Decode a versionCode

Topics: versionCode & versionName Strategy

The scheme from the lesson encodes major.minor.patch, a build number and a flavor digit as M…MMPPBBF. Write the inverse: decode(10402070) returns ("1.4.2", 7, 0). Return None for codes that can't be valid (zero, negative or above Play's limit of 2100000000).

python · try it yourself
def decode(code):
    # TODO: peel off the digits from the right: flavor (1), build (2), patch (2), minor (2), major (rest)
    return None

for code in [10402070, 20000121, 2099999999, 0, 2100000001]:
    print(code, "->", decode(code))
10402070 -> None
20000121 -> None
2099999999 -> None
0 -> None
2100000001 -> None

Expected output:

text
10402070 -> ('1.4.2', 7, 0)
20000121 -> ('2.0.0', 12, 1)
2099999999 -> ('209.99.99', 99, 9)
0 -> None
2100000001 -> None
Show solution
python
def decode(code):
    if code <= 0 or code > 2_100_000_000:
        return None
    code, flavor = divmod(code, 10)
    code, build = divmod(code, 100)
    code, patch = divmod(code, 100)
    major, minor = divmod(code, 100)
    return (f"{major}.{minor}.{patch}", build, flavor)

Exercise 3: Parse aapt2 dump badging

Topics: Inspecting APKs, Build Types

A verification step reads aapt2 dump badging output. Return a dict with package, versionCode (int), versionName, minSdk (int), targetSdk (int), permissions (sorted list) and debuggable (bool).

python · try it yourself
BADGING = """package: name='com.example.hello.free' versionCode='10402070' versionName='1.4.2' platformBuildVersionName='16' platformBuildVersionCode='36' compileSdkVersion='36' compileSdkVersionCodename='16'
minSdkVersion:'24'
targetSdkVersion:'36'
uses-permission: name='android.permission.INTERNET'
uses-permission: name='com.google.android.gms.permission.AD_ID'
application-label:'Hello'
application-debuggable
launchable-activity: name='com.example.hello.MainActivity'  label='' icon=''"""

def parse_badging(text):
    # TODO: use regular expressions on the lines above
    return {}

info = parse_badging(BADGING)
for key in ["package", "versionCode", "versionName", "minSdk", "targetSdk", "permissions", "debuggable"]:
    print(f"{key}: {info.get(key)!r}")
package: None
versionCode: None
versionName: None
minSdk: None
targetSdk: None
permissions: None
debuggable: None

Expected output:

text
package: 'com.example.hello.free'
versionCode: 10402070
versionName: '1.4.2'
minSdk: 24
targetSdk: 36
permissions: ['android.permission.INTERNET', 'com.google.android.gms.permission.AD_ID']
debuggable: True
Show solution
python
import re

def parse_badging(text):
    pkg = re.search(r"^package: name='([^']*)' versionCode='(\d*)' versionName='([^']*)'", text, re.M)
    return {
        "package": pkg.group(1),
        "versionCode": int(pkg.group(2)),
        "versionName": pkg.group(3),
        "minSdk": int(re.search(r"^minSdkVersion:'(\d+)'", text, re.M).group(1)),
        "targetSdk": int(re.search(r"^targetSdkVersion:'(\d+)'", text, re.M).group(1)),
        "permissions": sorted(re.findall(r"^uses-permission: name='([^']*)'", text, re.M)),
        "debuggable": bool(re.search(r"^application-debuggable
quot;, text, re.M)), }

Exercise 4: Release gate

Topics: Verifying APKs, The Manifest Merger, Field Notes: Flavors, SDK Levels & CI

Combine the pieces into the check a release job runs before uploading. gate(info, cert_sha256, expected) returns a list of problems (empty = ship it): wrong certificate, debuggable build, a permission not in the allowlist, targetSdk below the required level, or a versionCode not above the last uploaded one.

python · try it yourself
def gate(info, cert_sha256, expected):
    problems = []
    # TODO: five checks, one message each
    return problems

expected = {"cert": "0fe0f229", "permissions": {"android.permission.INTERNET"},
            "min_target": 35, "last_code": 10402060}
good = {"versionCode": 10402070, "targetSdk": 36, "debuggable": False,
        "permissions": ["android.permission.INTERNET"]}
bad = {"versionCode": 10402050, "targetSdk": 34, "debuggable": True,
       "permissions": ["android.permission.INTERNET", "android.permission.READ_CONTACTS"]}
print(gate(good, "0fe0f229", expected) or "ship it")
for p in gate(bad, "deadbeef", expected):
    print("-", p)
ship it

Expected output:

text
ship it
- signed with deadbeef, expected 0fe0f229
- debuggable build
- unexpected permission android.permission.READ_CONTACTS
- targetSdk 34 < 35
- versionCode 10402050 is not above 10402060
Show solution
python
def gate(info, cert_sha256, expected):
    problems = []
    if cert_sha256 != expected["cert"]:
        problems.append(f"signed with {cert_sha256}, expected {expected['cert']}")
    if info["debuggable"]:
        problems.append("debuggable build")
    for perm in sorted(set(info["permissions"]) - expected["permissions"]):
        problems.append(f"unexpected permission {perm}")
    if info["targetSdk"] < expected["min_target"]:
        problems.append(f"targetSdk {info['targetSdk']} < {expected['min_target']}")
    if info["versionCode"] <= expected["last_code"]:
        problems.append(f"versionCode {info['versionCode']} is not above {expected['last_code']}")
    return problems

Exercise 5: Fix the release build

Topics: Keep Rules, Mapping Files & Retrace, buildConfigField, resValue & Placeholders

This app reads a formatter class by name from BuildConfig.FORMATTER (so each flavor can pick one), and the release build has two problems. The session shows the first; fix the build script and keep rules so that assembleRelease succeeds and the mapping shows both formatters kept under their own names. (Copy the session into the Android image or any machine with AGP 9.4 to try your fix.)

bash · try it yourself
mkdir -p hello/app/src/main/java/com/example/hello && cd hello
cat > settings.gradle.kts <<'KTS'
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
dependencyResolutionManagement { repositories { google(); mavenCentral() } }
rootProject.name = "hello"
include(":app")
KTS
echo 'plugins { id("com.android.application") version "9.4.1" apply false }' > build.gradle.kts
cat > app/src/main/AndroidManifest.xml <<'XML'
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application android:label="Hello">
        <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
printf 'package com.example.hello;\npublic interface Formatter { String format(int cents); }\n' > app/src/main/java/com/example/hello/Formatter.java
printf 'package com.example.hello;\npublic class EuroFormatter implements Formatter { public String format(int c) { return c / 100 + " EUR"; } }\n' > app/src/main/java/com/example/hello/EuroFormatter.java
printf 'package com.example.hello;\npublic class DollarFormatter implements Formatter { public String format(int c) { return "
quot; + c / 100; } }\n' > app/src/main/java/com/example/hello/DollarFormatter.java cat > app/src/main/java/com/example/hello/MainActivity.java <<'JAVA' package com.example.hello; public class MainActivity extends android.app.Activity { @Override protected void onCreate(android.os.Bundle state) { super.onCreate(state); String text; try { Formatter f = (Formatter) Class.forName(BuildConfig.FORMATTER).getDeclaredConstructor().newInstance(); text = f.format(1999); } catch (Exception e) { text = e.toString(); } android.widget.TextView view = new android.widget.TextView(this); view.setText(text); setContentView(view); } } JAVA gradle wrapper > /dev/null cat > app/build.gradle.kts <<'KTS' plugins { id("com.android.application") } android { namespace = "com.example.hello" compileSdk = 36 defaultConfig { applicationId = "com.example.hello"; minSdk = 24; targetSdk = 36; versionCode = 1; versionName = "1.0" } flavorDimensions += "market" productFlavors { create("eu") { dimension = "market"; buildConfigField("String", "FORMATTER", "\"com.example.hello.EuroFormatter\"") } create("us") { dimension = "market"; buildConfigField("String", "FORMATTER", "\"com.example.hello.DollarFormatter\"") } } buildTypes { release { isMinifyEnabled = true; proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") } } } KTS touch app/proguard-rules.pro ./gradlew -q assembleRelease 2>&1 | grep -A2 'What went wrong'
* What went wrong:
A problem occurred configuring project ':app'.
>                         Product Flavor 'eu' contains custom BuildConfig fields, but the feature is disabled.
Show solution

Problem 1 is in the output: BuildConfig fields need the feature switched on. Add buildFeatures { buildConfig = true } inside android {}. Problem 2 then appears only at runtime: both formatters are reached only through Class.forName, so R8 removes them from the release builds. Keep every implementation of the interface with its constructor:

proguard
# app/proguard-rules.pro: formatters are loaded by name from BuildConfig.FORMATTER
-keep class * implements com.example.hello.Formatter { <init>(); }

Check with grep '^com.example' app/build/outputs/mapping/euRelease/mapping.txt: both EuroFormatter and DollarFormatter appear mapped to themselves. (Keeping only the flavor's own formatter would need a per-flavor rule file: proguardFiles(...) inside each create(...) block.)

Test yourself

In Exercise 5, why is a keep rule needed even after the build succeeds?

  1. R8 needs it to compile
  2. The formatters are only reached through Class.forName, so R8 removes them and the release build fails at runtime
  3. BuildConfig requires keep rules
  4. Keep rules speed up the build

Which check in Exercise 4's gate catches a build signed with the debug key?

  1. targetSdk
  2. the certificate digest comparison
  3. versionCode
  4. permissions