Android R8
Android R8
--------------
1. Introduction to R8
2. R8 vs ProGuard
- Historical Context: Before R8, Android used ProGuard for code shrinking and
obfuscation. ProGuard optimized bytecode, but required additional steps to convert
it to DEX code.
- R8 Advantage: Unlike ProGuard, R8 directly compiles bytecode to optimized DEX
code, reducing the steps involved and improving efficiency.
3. Key Features of R8
- Code Shrinking: Detects and removes unused classes, methods, and variables,
particularly useful for third-party libraries where only a small portion of it is
used.
- Resource Shrinking: Eliminates unused resources.
- Optimization: Optimizes code for performance, which helps to improve the
runtime performance and reduces DEX file size.
- Obfuscation: Obfuscates the code by renaming classes, methods, and variables
to random names, making it difficult to reverse engineer the app.
4. R8 Modes
5. Proguard rules
- ProGuard rules are the configurations that guide the ProGuard tool in
performing code shrinking, obfuscation, and optimization. R8 uses the same
configuration specification language as ProGuard, and tries to be compatible with
ProGuard.
- Common Proguard Rules
- Keep Rules:
Keep rules prevent specific classes, methods, or fields from
being removed or obfuscated during the optimization process.
// To keep an entire class:
-keep class com.example.MyClass { *; }
// To keep a specific method within a class:
-keep class com.example.MyClass { void myMethod(); }
- Keep Names:
To retain the original names of specific classes, methods, or
fields during obfuscation.
// To keep the name of a class:
-keepnames class com.example.MyClass
// To keep the name of a specific method within a class:
-keepnames class com.example.MyClass { void myMethod(); }
- Keep Attributes:
To retain certain attributes or annotations during the
optimization process.
// To keep the Signature attribute:
-keepattributes Signature
- Optimization Rules:
To control specific optimizations by enabling or disabling them.
// To disable arithmetic simplification optimization:
-optimizations !code/simplification/arithmetic
5. To note
- Lets have a look into the known issues with libraries that use reflection.
android {
buildTypes {
getByName("release") {
// Enables code shrinking, obfuscation, and optimization for only
// your project's release build type. Make sure to use a build
// variant with `isDebuggable=false`.
isMinifyEnabled = true
// Includes the default ProGuard rules files that are packaged with
// the Android Gradle plugin. To learn more, go to the section about
// R8 configuration files.
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
...
}