Code Shrinking and Optimization with R8

What is R8?

R8 is a compiler that replaces the Proguard tool in the Android Gradle Plugin (AGP) version 3.4.0 and later. Its primary function is to shrink and optimize code, making it more compact and efficient. R8 achieves better results than Proguard, with a 10% compaction rate compared to 8.5%.

Stages of R8

The R8 compiler performs several stages to reduce the size of your final APK:

  • Desugaring: Allows the use of Java 8 and above API features without worrying about support.
  • Code shrinking: Removes unused code from your app, including unused code in library dependencies.
  • Resource shrinking: Identifies and eliminates unused resources.
  • Obfuscation: Renames classes and fields to protect against reverse engineering.
  • Optimizing code: Reduces app footprint and improves efficiency by removing unreachable code branches.

Configuring Code Shrinking

To enable code shrinking, set the minifyEnabled flag to true in your build.gradle file. You can also enable resource shrinking by setting shrinkResources to true.

android {
    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
        }
    }
}

Understanding Proguard Rule Schema

Proguard rules are used to configure R8. A typical rule consists of three sections:

  • Keep option: Defines what to retain, such as classes or methods.
  • Token type: Specifies the type of target entity, such as class or enum.
  • Wildcards: Allow for pattern matching in names.

Writing Your Own R8 Rules

While the default rules shipped with AGP are sufficient, you may need to write custom rules to keep specific classes or methods. Use the keep keyword to retain targets, and specify fully qualified class names.

-keep class com.example.MyClass { *; }

Resource Shrinking

Resource shrinking is performed after code shrinking. Use a keep.xml file in your res/raw folder to specify resources to retain.

Debugging R8 Errors

Use the retrace tool to identify missing resources or classes. Add specific keep rules to fix issues, and use keepattributes to retain meta properties like line numbers and source file names.

Aggressive Shrinking Options

Enable aggressive shrinking by setting the android.enableR8.fullMode property to true in your gradle.properties file. This will result in more rigorous optimizations.

android.enableR8.fullMode=true

Leave a Reply

Your email address will not be published. Required fields are marked *