Generated banner for R8 Analyzer
Generated logo for R8 Analyzer

R8 Analyzer

Android (Google)OfficialCreated by Google LLCDistributed by Android (Google)

  • Skill
  • Review and audit
  • Software development
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

Analyzes Android build files and R8 keep rules to identify redundancies, broad package-wide rules, and rules that subsume library consumer keep rules. Use this skill when developers want to optimize their Android app's size, remove redundant or overly broad keep rules, or troubleshoot ProGuard configurations. Don't use for general Gradle build errors, Compose UI performance, or runtime CPU profiling.
— the description by Google LLC

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The r8-analyzer skill provides a structured approach to auditing Android ProGuard and R8 keep rules. By analyzing build configurations and generating reports on rule impact, it helps developers identify redundant or overly broad rules that negatively affect app size and obfuscation efficiency. The skill supports both modern AGP 9.3+ workflows via standalone tasks and legacy configurations through temporary R8 version updates, ensuring comprehensive coverage for various project setups.

What it does

  • Identifies redundant or overly broad R8 keep rules.
  • Detects rules that subsume library consumer keep rules.
  • Generates impact metrics and scores for existing keep rules.
  • Validates build configuration settings for optimal R8 usage.
  • Provides actionable remediation guidance based on rule patterns.
  • Supports automated report generation for release build variants.

When to use it

  • When you need to reduce the final size of your Android application.
  • When troubleshooting unexpected behavior in ProGuard or R8 configurations.
  • When you suspect that your keep rules are too broad or redundant.
  • When auditing library dependencies for inefficient keep rule declarations.

Advantages

  • Provides quantitative impact metrics for specific keep rules.
  • Automates the extraction and analysis of complex R8 configuration data.
  • Offers clear, standardized reporting formats for build optimizations.
  • Helps maintain cleaner and more efficient ProGuard configuration files.

Usage examples

“Analyze my app's R8 configuration to find redundant keep rules.”
The agent will inspect your build files, run the appropriate R8 analysis task, and generate a report detailing high-impact and redundant rules.
“Why is my Android app size larger than expected? Check my keep rules.”
The agent will perform a deep dive into your R8 rules to identify if overly broad rules are preventing effective code shrinking.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/android/r8-analyzer/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip r8-analyzer.zip -d .agents/skills

Documentation by Google LLC

Step 1. Setup and configuration check

  • Inspect build.gradle, build.gradle.kts, and gradle.properties.

  • Use references/CONFIGURATION.md to identify missing optimizations.

  • AGP : If the version is lower than 9.3, suggest migration to 9.3 for the simplified optimization {} DSL and the Configuration Analyzer task.

  • Full mode : Verify android.enableR8.fullMode=false is removed from the gradle.properties file.

Step 2. Analysis path selection

  • Inspect build.gradle, build.gradle.kts, settings.gradle, settings.gradle.kts, gradle.properties, and libs.versions.toml to get the AGP and R8 versions. An R8 version pinned in settings.gradle(.kts) replaces the R8 bundled with AGP.

  • Find the app module (usually app) and a build variant with R8 enabled (usually release). The following commands use them as <module> and <Variant>, for example :app:minifyReleaseWithR8.

  • The helper scripts are in this skill's scripts/ directory. In the following commands, <skill_dir> is this skill's directory. Run every command from the project root.

  • If AGP >= 9.3.0 : Proceed to Path A (Standalone Task).

  • If AGP < 9.3.0 : Proceed to Path B (Quantitative).

Path A: Standalone Gradle task (AGP >= 9.3.0)
  • Step 1: Check requirements : Python and the protobuf package 6.33.4 or later are mandatory (used by scripts/keep_radius_pb2.py). Install it with pip install "protobuf>=6.33.4"; versions lower than 6.33.4 fail on import with a VersionError or ImportError.

  • Step 2: Run standalone task on R8-enabled build : For the module and variant you found during path selection, run ./gradlew :<module>:analyze<Variant>R8Config (for example, ./gradlew :app:analyzeReleaseR8Config). It generates the report in <module>/build/reports/r8/ (for example, app/build/reports/r8/r8-config-analyzer-release.pb). You must wait for this command to finish before proceeding.

  • Step 3: Convert to JSON : You must explicitly run the conversion script scripts/convert_pb_to_json.py as python3 <skill_dir>/scripts/convert_pb_to_json.py with arguments <module>/build/reports/r8 and tmp/keepradius/keepruleradius.json. Wait for this command to finish.

  • Step 4: Analyze : You must explicitly run the analysis script scripts/analyze.py by executing python3 <skill_dir>/scripts/analyze.py tmp/keepradius/keepruleradius.json. This outputs tmp/keepradius/analysis_result.txt. Wait for this command to finish.

Path B: Invoke R8 release build (AGP < 9.3.0)
  • Step 1: Check requirements : Python and the protobuf package 6.33.4 or later are mandatory: pip install "protobuf>=6.33.4".

  • Step 2: Generate and analyze : You must run the shell commands described in references/FULL_BUILD_CONFIG_ANALYZER.md to temporarily update the R8 version in settings.gradle(.kts) to 9.4.34 or later (so R8 generates the report), generate the proto report in tmp/r8analysis/, convert it to tmp/r8analysis/keepruleradius.json, analyze the result, and revert the temporary settings.gradle(.kts) change.

  • Step 3: Analyze : Verify that the analysis outputs tmp/r8analysis/analysis_result.txt for scores and rule impact metrics.

Step 3. Report generation

  • Format : Follow references/REPORT_FORMAT.md strictly.

  • Redundant rules : Check keep rules against references/INSPECT-RULES.md. If a keep rule matches a pattern in references/INSPECT-RULES.md, include the guidance and remediation from that reference alongside the impact metrics.

  • Input : Extract metrics (Scores, Impacts, Example Classes, rule origins) directly from the generated file tmp/keepradius/analysis_result.txt if using Path A, or tmp/r8analysis/analysis_result.txt if using Path B.

  • Output : Short progress updates are fine while Gradle runs; the final message is the report only. Output only the raw Markdown report in the chat. Do not output conversational filler (for example, "Here is your report..."). Do not provide recommendations, next steps, or any other text outside of the sections defined in references/REPORT_FORMAT.md. Do not mention the path used for analysis of the configuration.

Constraints

  • Strict output limit: The final output must strictly be the Markdown report and nothing else.

  • No code changes : Research and suggest only; do not modify project files. Create files only under tmp/ (analysis output, the settings backup, and any scratch scripts), and never write the report to a file. The one exception is the temporary R8 classpath in settings.gradle(.kts) that Path B needs when the project doesn't already pin R8 9.4.34 or later: ask the user first when running interactively, and revert it after the analysis (see references/FULL_BUILD_CONFIG_ANALYZER.md). If that change is needed but the user says no, or asks you not to edit build files, report rule-level and build file findings without scores and say why.

  • No placeholder scores : Never print N/A% as a score.

  • No redundancy: Do not explain R8 benefits or reference skill internal files in the report.

  • Focus: Omit sections (for example, Subsumed Rules, Configuration) if no issues or items are found.

Files

references/android/topic/performance/app-optimization/enable-app-optimization.md

Android skills

View on GitHub

R8 Analyzer

Use the R8 Analyzer Android skill to analyze build files and identify redundant, broad, or subsumed keep rules. To install the skill from the Android CLI, run:

android skills add r8-analyzer

<br />

For the best user experience, you should optimize your app to make it as small and fast as possible. Our app optimizer, called R8, streamlines your app by removing unused code and resources, rewriting code to optimize runtime performance, and more. To your users, this means:

  • Faster startup time

  • Reduced memory usage

  • Improved rendering and runtime performance

  • Fewer ANRs

[!IMPORTANT] Important: You should always enable optimization for your app's release build; however, you probably don't want to enable it for tests or libraries. For more information about using R8 with tests, see Test and troubleshoot the optimization. For more information about enabling R8 from libraries, see Optimization for library authors.

R8 optimization overview

R8 uses a multi-phase process to optimize your app for size and speed. Key operations include the following:

  • Code shrinking (also known as tree shaking) : R8 identifies and removes unreachable code from your application and its library dependencies. By analyzing the entry points of your app (such as Activities or Services defined in the manifest), R8 builds a graph of referenced code and removes anything that remains unreferenced.

  • Logical optimizations: R8 rewrites your code to improve execution efficiency and reduce overhead. Key techniques include:

    • Method inlining: R8 replaces a method call site with the actual body of the called method. This eliminates the overhead of a function call and lets R8 conduct further optimizations.

    • Class merging: R8 combines sets of classes and interfaces into a single class. This reduces the number of classes in the app, lowering memory pressure and improving startup speed.

  • Obfuscation (also known as minification) : To reduce the size of the DEX file, R8 shortens the names of classes, fields, and methods (for example, com.example.MyActivity could become a.b.a).

Since 8.12.0 version of Android Gradle Plugin (AGP), R8 also optimizes resources as part of its optimization phases. For more information, see Optimized resource shrinking.

Enable optimization

To enable app optimization for your app use the appropriate DSL based on your project's AGP version. We recommend enabling app optimization only in the final version of your app that you test before publishing---usually your release build---because the optimizations increase the build time of your project and can make debugging harder due to the way it modifies code.

For AGP versions 9.3 and higher

To enable app optimization for AGP 9.3 and higher:

  • Set enable = true in the optimization block in your release build's app-level build script.

  • Add your keep rules to a file with the suffix .keep in the src/<variant>/keepRules source set. For example, src/main/keepRules/custom-rules.keep.

[!NOTE] Note: The updated DSL enables both code and resource optimization. It also includes a set of default keep rules for the Android platform, equivalent to "proguard-android-optimize.txt". To omit the default rules, see Omit default rules.

Kotlin
android {
    buildTypes {
        release {
            optimization {
                enable = true // Enables code and resource optimizations.
            }
        }
    }
}
Groovy
android {
    buildTypes {
        release {
            optimization {
                enable = true // Enables code and resource optimizations.
            }
        }
    }
}
Legacy DSL for AGP versions lower than 9.3

To enable app optimization, set isMinifyEnabled = true (for code optimization) and isShrinkResources = true (for resource optimization) in your release build's app-level build script. We recommend that you always enable both settings.

Legacy DSL (Kotlin)
android {
    buildTypes {
        release {

            // Enables code optimizations.
            isMinifyEnabled = true

            // Enables resource shrinking.
            isShrinkResources = true

            proguardFiles(
                // Default file with automatically generated optimization rules.
                getDefaultProguardFile("proguard-android-optimize.txt"),

                ...
            )
            ...
        }
    }
    ...
}
Legacy DSL (Groovy)
android {
    buildTypes {
        release {

            // Enables code optimizations.
            minifyEnabled = true

            // Enables resource shrinking.
            shrinkResources = true

            // Default file with automatically generated optimization rules.
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt')

            ...
        }
    }
}

Improve R8 optimization

The performance benefits of R8 are directly correlated to how much of your codebase R8 is able to optimize. To get the maximum benefits out of R8, follow best practices:

To help you refine keep rules, use the R8 Configuration Analyzer.

The R8 Configuration Analyzer lets you do the following:

  • Track and improve the overall R8 configuration quality by monitoring the metrics provided by the R8 Configuration Analyzer report.

  • Find the broadest keep rules - those which prevent the most optimization

  • and understand what optimization they prevent to refine them.

The R8 Configuration Analyzer is available in AGP version 9.3.0-alpha05 or from R8 version 9.3.7-dev. For more information, see Analyze R8 configuration.

Optimize resource shrinking for even smaller apps

The 8.12.0 version of AGP introduces optimized resource shrinking, which aims to integrate resource and code optimization to create even smaller and faster apps. Before optimized resource shrinking, Android Asset Packaging Tool (AAPT2) generated keep rules that effectively treating resource shrinking separately from code, often retaining inaccessible code or resources that referenced each other.

With optimized resource shrinking, resources are considered like a part of program code, forming the reference graph. When a collection of code or resources is not referenced, it is not protected by a keep rule, and can be removed.

Enable optimized resource shrinking

To enable the new optimized resource shrinking pipeline for AGP 8.12 or 8.13, add the following to your project's gradle.properties file:

android.r8.optimizedResourceShrinking=true

If you are using AGP 9.0.0 or a newer version, you don't need to set android.r8.optimizedResourceShrinking=true. Optimized resource shrinking is automatically applied when isShrinkResources = true is enabled in your build configuration.

Verify and configure R8 optimization settings

To enable R8 to use its full optimization capabilities, remove the following line from your project's gradle.properties file, if it exists:

android.enableR8.fullMode=false

Note that enabling app optimization makes stack traces difficult to understand, especially if R8 renames class or method names. To get stack traces that correctly correspond to your source code, see Recover the original stack trace.

If R8 is enabled, you should also create Startup Profiles for even better startup performance.

If you enable app optimization and it causes errors, here are some strategies to fix them:

[!CAUTION] Caution: Tools that replace or modify R8's output can negatively impact runtime performance. R8 is careful about including and testing many optimizations at the code level, in DEX layout, and in correctly producing Baseline Profiles - other tools producing or modifying DEX files can break these optimizations, or otherwise regress performance.

If you are interested in optimizing your build speed, see Configure how R8 runs for information on how to configure R8 based on your environment.

AGP and R8 version behavior changes

The following table outlines the key features introduced in various versions of the Android Gradle Plugin (AGP) and the R8 compiler.

AGP versionFeatures introduced
9.3Simplified DSL: New `optimization {}` block enables requires less configuration- optimized resource shrinking is always enabled, default Android keep rules are opt-out. <br /> `keepRules` source set: If you use the new DSL, you must place your keep rules in the src/<variant>/keepRules source set, in files with the suffix .keep. The source sets are also compatible with the legacy DSL. <br /> KMP (Kotlin MultiPlatform) consumer rules: KMP no longer requires setting publish = true, and supports the src/<variant>/keepRules source set with the .keep extension. <br /> Note that the legacy DSL is still supported.
9.1Classes repackaged by default: R8 repackages classes (moving them to the unnamed package, at the top level) to compact DEX further, eliminating the need to specify -repackageclasses option. For information about how this works and how to opt out, see global options.
9.0Optimized resource shrinking: Enabled by default (controlled using android.r8.optimizedResourceShrinking). Optimized resource shrinking helps integrate resource shrinking with the code optimization pipeline, leading to smaller, faster apps. By optimizing both code and resource references simultaneously, it identifies and removes resources referenced exclusively from unused code. This is a significant improvement over the previous separate optimization processes. This is especially useful for apps that share substantial resources and code across different form factor verticals, with measured improvements of over 50% in app size. The resulting size reduction leads to smaller downloads, faster installations, and a better user experience with faster startup, improved rendering, and fewer ANRs. Library rule filtering: Support for global options (for example, -dontobfuscate) in library consumer rules has been dropped, and apps will filter them out. For more information, see Add global options. Kotlin null checks: Optimized by default (controlled using -processkotlinnullchecks). This version also introduced significant improvements in build speed. For more information, see Global options for additional optimization. Optimize specific packages: You can use packageScope to optimize specific packages. This is in experimental support. For more information, see Optimize specified packages with packageScope. Optimized by default: Support for getDefaultProguardFile("proguard-android.txt") has been dropped, because it includes -dontoptimize, which should be avoided. Instead, use "proguard-android-optimize.txt". If you need to globally disable optimization in your app, add the flag manually to a proguard file.
8.12Optimized resource shrinking: Initial support added (controlled using android.r8.optimizedResourceShrinking). Optimized resource shrinking helps integrate resource shrinking with the code optimization pipeline. You must manually enable it in this version of AGP. Logcat retracing: Support for automatic retracing in the Android Studio Logcat window.
8.6Improved retracing: Includes filename and line number retracing by default for all minSdk levels (previously required minSdk 26+ in version 8.2). Updating R8 helps ensure that stack traces from obfuscated builds are readily and clearly readable. This version improves how line numbers and source files are mapped, making it easier for tools like the Android Studio Logcat to automatically retrace crashes to the original source code.
8.0Full mode by default: R8 full mode provides significantly more powerful optimization. It is enabled by default. You can opt out using android.enableR8.fullMode=false.
7.0Full mode available: Introduced as an opt-in feature using android.enableR8.fullMode=true. Full mode applies more powerful optimizations by making stricter assumptions about how your code uses reflection and other dynamic features. While it reduces app size and improves performance, it might require additional keep rules to prevent necessary code from being stripped.

Use R8 with other build systems

While AGP is the recommended and officially supported build system for Android apps, you might use an alternative build system like Bazel. If you're using Bazel, you can integrate R8 into your build pipeline to shrink, obfuscate, and optimize your app.

For information about optimizing an Android app using Bazel, see Bazel's rules_android documentation. Note that Bazel isn't officially supported for Android app development.

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
Google LLC
Publisher
Android (Google) (Official)
Distributed by
Android (Google)
Source
android/skills · performance/r8-analyzer · commit bf68e2d
Licence
Apache License 2.0 (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE.txt)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Google LLC or Android (Google).

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download r8-analyzer.zip