TExcelTAD
Home › Mobile Build Pipelines: Gradle/AGP, Xcode, SwiftPM & Fastlane › R8: Shrinking, Optimizing & Obfuscating

R8: Shrinking, Optimizing & Obfuscating

R8 is the Android compiler that turns bytecode into dex for release builds. With isMinifyEnabled = true it does four things in one pass:

  1. Shrinking (tree shaking): starting from entry points (activities and other components in the manifest, plus anything a keep rule names), it follows every reference and deletes classes, methods and fields nobody reaches.
  2. Optimizing: inlining, constant folding, class merging, removing dead branches (if (BuildConfig.DEBUG) in release disappears).
  3. Obfuscating: renaming what's left to short names like a, b, which also shrinks the dex.
  4. Dexing: writing classes.dex, the job D8 does for debug builds.

It replaced ProGuard in AGP 3.4 and reads the same rule syntax. Since AGP 8 it runs in full mode by default, which optimizes more aggressively than ProGuard-compatible mode did.

R8 is part of AGP

There's nothing to install: R8 ships inside the Android Gradle Plugin, so it's available wherever AGP is, including offline. The session builds with --offline to prove it, then compares debug and release:

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
cat > app/src/main/java/com/example/hello/Scoreboard.java <<'JAVA'
package com.example.hello;

import java.util.ArrayList;
import java.util.List;

public final class Scoreboard {
    private final List<Integer> scores = new ArrayList<>();
    public void add(int s) { if (s > 0) scores.add(s); else throw new IllegalArgumentException("bad score " + s); }
    public int total() { int t = 0; for (int s : scores) t += s; return t; }
    public String describe() { return scores.size() + " scores, total " + total(); }
    public String exportCsv() { return scores.toString(); }          // never called
}
JAVA
cat > app/src/main/java/com/example/hello/MainActivity.java <<'JAVA'
package com.example.hello;

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

public class MainActivity extends Activity {
    @Override protected void onCreate(Bundle state) {
        super.onCreate(state);
        Scoreboard board = new Scoreboard();
        for (int i = 0; i < getIntent().getIntExtra("n", 3); i++) board.add(i + 1);
        Scoreboard bonus = new Scoreboard();
        bonus.add(getTaskId());
        TextView view = new TextView(this);
        view.setText(board.describe() + " / " + bonus.describe());
        setContentView(view);
    }
}
JAVA
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" }
    buildTypes {
        release {
            isMinifyEnabled = true
            proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
        }
    }
}
KTS
touch app/proguard-rules.pro
gradle wrapper > /dev/null
./gradlew --offline assembleDebug assembleRelease | grep -E 'R8|^BUILD'
for apk in debug/app-debug release/app-release-unsigned; do
  unzip -l app/build/outputs/apk/$apk.apk classes.dex | awk -v n=$apk '/classes.dex/ { print n ": classes.dex " $1 " bytes" }'
done
ls app/build/outputs/mapping/release/
sed -n '1,3p;8,$p' app/build/outputs/mapping/release/mapping.txt
> Task :app:minifyReleaseWithR8
BUILD SUCCESSFUL in 19s
debug/app-debug: classes.dex 2420316 bytes
release/app-release-unsigned: classes.dex 2424 bytes
configanalyzer.html
configanalyzer.pb
configuration.txt
mapping.prt
mapping.txt
seeds.txt
usage.txt
# compiler: R8
# compiler_version: 9.4.24
# min_api: 24
com.example.hello.MainActivity -> com.example.hello.MainActivity:
# {"id":"sourceFile","fileName":"MainActivity.java"}
    1:1:void <init>():7:7 -> <init>
    1:8:void onCreate(android.os.Bundle):9:16 -> onCreate
com.example.hello.Scoreboard -> a:
# {"id":"sourceFile","fileName":"Scoreboard.java"}
    java.util.List scores -> a
      # {"id":"com.android.tools.r8.residualsignature","signature":"Ljava/util/ArrayList;"}
    1:2:void <init>():6:7 -> <init>
    1:1:void add(int):8:8 -> a
    1:1:java.lang.String describe():10:10 -> b
    2:2:int total():9:9 -> b
    2:2:java.lang.String describe():10 -> b
    3:3:java.lang.String describe():10:10 -> b

What happened:

  • Size. The debug dex holds our two classes plus the whole Kotlin standard library that AGP 9 adds to every app (see Dependencies & Unit Tests); none of it is used, so R8 drops it all.
  • MainActivity keeps its name. It's an entry point named in the manifest, and AAPT2 generates a keep rule for every component it finds there.
  • Scoreboard became a, its field scores became a, add became a. total() was inlined into describe() (both map to b, with line ranges telling which source lines came from where). exportCsv() is gone: nothing called it.
  • mapping.txt is the dictionary from new names back to old ones. Without it, a crash report from production reads at a.a(Unknown Source:3). The next lesson, Keep Rules, Mapping Files & Retrace, uses it.

The other files: usage.txt lists what was removed, seeds.txt what keep rules matched, configuration.txt every rule that applied (yours, AGP's defaults, AAPT2's and those shipped inside libraries), and configanalyzer.html is a report on which rules keep the most code.

Resource shrinking

isShrinkResources = true builds on R8: once code is shrunk, resources that no remaining code or resource references are removed too. It requires isMinifyEnabled. And AGP 9 refuses the old non-optimizing default rule file:

bash · try it yourself
mkdir -p hello/app/src/main/res/values && 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
echo '<manifest xmlns:android="http://schemas.android.com/apk/res/android"><application android:label="@string/app_name" /></manifest>' > app/src/main/AndroidManifest.xml
cat > app/src/main/res/values/strings.xml <<'XML'
<resources>
    <string name="app_name">Hello</string>
    <string name="old_promo">Spring sale! (nobody references this any more)</string>
</resources>
XML
gradle wrapper > /dev/null   # before the build script: a broken script would stop it too
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" }
    buildTypes {
        release {
            isMinifyEnabled = true
            isShrinkResources = true
            proguardFiles(getDefaultProguardFile("proguard-android.txt"))
        }
    }
}
KTS
./gradlew -q assembleRelease 2>&1 | grep -A1 'What went wrong'
sed -i 's/proguard-android.txt/proguard-android-optimize.txt/' app/build.gradle.kts
./gradlew -q assembleDebug assembleRelease
for apk in debug/app-debug release/app-release-unsigned; do
  echo "$apk: $(aapt2 dump resources app/build/outputs/apk/$apk.apk | grep -o 'string/[a-z_]*' | tr '\n' ' ')"
done
* What went wrong:
`getDefaultProguardFile('proguard-android.txt')` is no longer supported since it includes `-dontoptimize`, which prevents R8 from performing many optimizations. Instead use `getDefaultProguardFile('proguard-android-optimize.txt)`, and if needed, temporarily use `-dontoptimize` in a custom keep rule file while fixing breakages.
debug/app-debug: string/app_name string/old_promo
release/app-release-unsigned: string/app_name

Resources loaded by name at runtime (getIdentifier("promo_" + season, "string", …)) can't be seen by the shrinker. Keep them with a res/raw/keep.xml containing tools:keep="@string/promo_*".

Turning it on safely

Enabling R8 on an existing app is a project, not a flag flip:

  1. Turn it on for a staging build type first and run your instrumented and manual tests against that build.
  2. Watch for the classic breakages: reflection, JSON serialization of model classes (Gson, Moshi without codegen), JNI, classes named in XML or strings, and enum.valueOf.
  3. Add keep rules narrowly (the next lesson), never -dontobfuscate/-dontshrink "just to be safe": they throw away most of the benefit.
  4. Archive mapping.txt with every release build. It's different for every build, and you need the exact one to read that build's crashes.

Test yourself

Why did MainActivity keep its name while Scoreboard became a?

  1. R8 never renames activities by luck
  2. AAPT2 generates keep rules for every component named in the manifest
  3. MainActivity is public
  4. Scoreboard is final

Which file do you need to turn at a.b(Unknown Source:2) into a readable stack trace?

  1. usage.txt
  2. seeds.txt
  3. mapping.txt from the same build
  4. configuration.txt

What does isShrinkResources = true require?

  1. isDebuggable = true
  2. isMinifyEnabled = true (it works from R8's view of reachable code)
  3. An App Bundle
  4. proguard-android.txt