The next step in the release process is to enable code obfuscation. Open your build.gradle configuration and update it as follows:
... buildTypes { ... release { debuggable false minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro' } } ...
The configuration we just added will shrink resources and perform obfuscation. For the obfuscation, we will use ProGuard. ProGuard is a free Java class file shrinker, optimizer, obfuscator, and preverifier. It performs detection of unused classes, fields, methods, and attributes. It optimizes bytecode as well!
In most cases, the default ProGuard configuration (the one we use) is enough to remove all the unused code. However, it can happen for ProGuard to remove the code your app actually needs! For that purpose, you must define the ProGuard configuration to keep those classes. Open your project's ProGuard configuration file and append the following:
-keep public class MyClass
Here is the list of ProGuard directives you will need to add if using some libraries:
- Retorfit:
-dontwarn retrofit.** -keep class retrofit.** { *; } -keepattributes Signature -keepattributes Exceptions
- Okhttp3:
-keepattributes Signature -keepattributes *Annotation* -keep class okhttp3.** { *; } -keep interface okhttp3.** { *; } -dontwarn okhttp3.** -dontnote okhttp3.** # Okio -keep class sun.misc.Unsafe { *; } -dontwarn java.nio.file.* -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
- Gson:
-keep class sun.misc.Unsafe { *; } -keep class com.google.gson.stream.** { *; }
Update your proguard-rules.pro file with these lines.