Optimizing ProGuard Configurations for Android Builds
Core ProGuard Directives
To ensure proper code shrinking and obfuscation in an Android project, define essential rules within the proguard-rules.pro file. This configuration prevents essential system classes from being mangled and maintains the integrity of your application components.
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontoptimize
-dontpreverify
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
-keepattributes *Annotation*
# Retain application lifecycle components
-keep public class * extends android.app.Fragment
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
# Suppress warnings for common support libraries
-ignorewarning
-dontwarn android.support.**
Protecting Reflection and Native Code
Reflection-heavy code, such as JNI interfaces or dynamically linked UI components, can break during obfuscation. Ensure these signatures remain identifiable by the runtime.
# Preserve native method signatures
-keepclasseswithmembernames class * {
native <methods>;
}
# Prevent obfuscation of view constructors for XML inflation
-keepclasseswithmembers class * {
public <init>(android.content.Context, android.util.AttributeSet);
}
# Keep Parcelable and Serializable implementations
-keep class * implements android.os.Parcelable {
public static final android.os.Parcelable$Creator *;
}
-keepnames class * implements java.io.Serializable
Handling Annotation-Based Frameworks
When using libraries like Afinal that rely heavily on Java annotations for dependancy injection or view binding, standard obfuscation might strip or mangle metadata, leading to runtime failures such as unresponsive UI events.
If you encounter issues where annotated methods or cllick listeners are not triggered after a release build, insure that the annotations are preserved and that the shrinking phase is configured correctly to prevent the removal of essential reflective code:
# Ensure annotation metadata is not removed
-keepattributes Signature
-keepattributes *Annotation*
# Preserve specific library components
-keep class net.tsz.afinal.** { *; }
-keep public class * extends net.tsz.afinal.**
# Disable shrinking if aggressive removal is causing runtime crashes
-dontshrink
Logging Configuration
For debugging production obfuscation issues, define mapping files and seed outputs. This generates files in the project root directory during the build process:
-dump proguard/class_files.txt
-printseeds proguard/seeds.txt
-printusage proguard/unused.txt
-printmapping proguard/mapping.txt