skip to content

With Android Gradle plugin 9.4, how do you turn on R8 for a release build, and what does a keep rule tell it?

level: middleimportance: must knowfreq 64%

answer

  1. release only, not debug
  2. the optimization block since 9.3
  3. reachable from manifest entry points
  4. shrink, optimize, rename
  5. keep option, modifiers, class spec

basics

~20 s

Since AGP 9.3, set optimization { enable = true } in the release build type (the older isMinifyEnabled and isShrinkResources still work); R8 then removes, rewrites and renames code and resources, and keep rules name what it must preserve.

solid answer

~40 s

In AGP 9.4 the current DSL is `optimization { enable = true }` inside `buildTypes.release`; it turns on code and resource optimization and includes default Android keep rules equivalent to `proguard-android-optimize.txt`. The legacy `isMinifyEnabled = true` plus `isShrinkResources = true` still works. R8 starts from entry points such as the activities and services in the manifest, removes everything unreachable, inlines and merges classes, and shortens names; full mode has been the default since AGP 8.0. Your own rules go in `.keep` files under `src/<variant>/keepRules`. A rule is a keep option, optional modifiers and a class specification: `-keepclassmembers class com.example.Dto { <fields>; }` keeps those fields if the class survives. A rule that lists no members keeps only the class and its no-argument constructor.

code

kotlin · 9 lines
kotlin
android {
    buildTypes {
        release {
            optimization {
                enable = true // code and resource optimization
            }
        }
    }
}

go deeper

for a junior

Know that R8 runs on release builds, shrinks and renames code, and that keep rules protect code it cannot see being used.

for a middle

Explain the AGP 9.3 optimization block versus isMinifyEnabled, where keep files live, and the difference between keep, keepclassmembers and keepnames.

for a senior

Write narrow rules against compiled names, prefer conditional and annotation-based rules, and check how much optimization each broad rule costs.

for a principal

Treat keep rules as owned configuration: who reviews them, how libraries ship their own, and how the release build is tested in CI.

## What R8 does to a release build **R8** is the Android Gradle plugin's optimizer. When optimization is on for a build type, R8 produces that build's DEX and does three kinds of work on the way: - **Code shrinking (tree shaking).** R8 starts from the app's entry points, such as the activities and services declared in the manifest, builds a graph of everything they reference, and removes the rest, in your code and in libraries. - **Logical optimizations.** It inlines methods into their call sites and merges classes and interfaces, which cuts method calls, class count and memory. - **Obfuscation (minification).** It shortens class, field and method names, so `com.example.MyActivity` may become `a.b.a`, and since AGP 9.1 it also repackages classes by default. Resources are part of the same graph: optimized resource shrinking, the default since AGP 9.0 when resource shrinking is on, removes resources that only unused code referenced. The result is a smaller, faster app with fewer ANRs, at the price of longer builds and harder debugging, which is why Google recommends turning it on for the release build and not for debug. ## Turning it on in AGP 9.4 | AGP | How to enable | Where your keep rules go | |---|---|---| | 9.3 and later | `optimization { enable = true }` in the release build type | `.keep` files under `src/<variant>/keepRules` | | Legacy DSL (still supported) | `isMinifyEnabled = true` and `isShrinkResources = true` | `proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")`, or the same `keepRules` folder | The new block enables both code and resource optimization and brings default Android keep rules equivalent to `proguard-android-optimize.txt`. Two older habits no longer apply: 1. AGP 9.0 dropped `getDefaultProguardFile("proguard-android.txt")`, because it contains `-dontoptimize`. 2. Setting `android.enableR8.fullMode=false` in `gradle.properties` opts out of **full mode**, the default since AGP 8.0. Full mode assumes less reflection and optimizes harder, so remove that line unless you need it. ## Anatomy of a keep rule A keep rule names a class (or its subclasses or implementations) and the members inside it to preserve: ```plaintext -<keep_option>[,<modifier>...] <class_specification> ``` The **keep option** decides what is protected: - `-keep` preserves the matched classes and members and blocks optimizing them, so use it sparingly. - `-keepclassmembers` preserves the listed members only if R8 keeps the class anyway. It allows the most optimization and is the usual choice. - `-keepclasseswithmembers` keeps a class and its members only if the class has all the listed members. - `-keepnames` and the other `names` options only stop renaming; unused code can still be removed. The equivalent `-keep,allowshrinking` reads more clearly. **Modifiers** loosen a rule: `allowoptimization`, `allowobfuscation`, `allowshrinking`, `allowaccessmodification` and `allowrepackage`, plus `includedescriptorclasses` to keep the types in kept signatures. The **class specification** uses fully qualified names as compiled: a Kotlin top-level function lives in a `FileNameKt` class, `internal` members are `public` in bytecode, and generics are erased. A rule that lists no members, such as `-keep class com.example.MyClass`, keeps the class and its default constructor only. ## Rules that do more than keep - `-if` makes a rule conditional: keep a member only for classes that match a pattern, which is how Jetpack Navigation keeps `fromBundle` only on `NavArgs` classes. - `-assumenosideeffects` tells R8 a method has no side effects, so it may drop calls to it when it optimizes; this is how a release build strips logging calls. - Libraries ship their rules inside the AAR, so a dependency's reflection usually needs nothing from you. ## Writing rules against compiled names R8 reads bytecode, so a rule must match what the Kotlin compiler produced, not the source: - A `suspend` function gains a trailing `kotlin.coroutines.Continuation` parameter and returns `java.lang.Object`; match that signature or use `...` for the parameters. - A nullable `Int?` compiles to `java.lang.Integer`, while `Int` is the primitive `int`. - A constructor is `<init>`, and `<fields>` or `<methods>` match every field or method of the class. Since AGP 9.3 the R8 Configuration Analyzer reports which of your rules are the broadest and what optimization each one blocks, which is the quickest way to find the rule that is costing the most. ## Where people go wrong - Testing only the debug build, where R8 never runs. - Keeping whole packages with `-keep class com.example.** { *; }` and losing most of the optimization. - Reading `-keepnames` as "keep".

  • How do you strip android.util.Log debug calls from the release build with R8?
    Add an `-assumenosideeffects` rule naming those methods, for example `-assumenosideeffects class android.util.Log { public static int d(...); public static int v(...); }`. R8 then treats calls to them as removable and drops them when it optimizes. The rule is a promise: if a listed method did have an effect you needed, that effect disappears too.
  • Why might a keep rule that names a class still leave its methods renamed or removed?
    A rule with no member list keeps only the class and its no-argument constructor; other members are still shrunk and renamed. List the members you need, such as `<fields>`, a method signature or `<init>(...)`, and match their compiled names and types, not the Kotlin source spelling.

R8 is a mover who packs only what is connected to the front door by a visible path. Anything you plan to fetch later by a name written on a note looks unused, so it stays behind unless you tag it with a keep rule.

  • R8 only renames classes and never removes code
  • A -keep rule with no members keeps every method and field of the class
  • -keepnames stops R8 from removing an unused class
  • Turn R8 on for debug builds too, as the recommended default
  • proguard-android.txt is still the safe default rules file