Code shrinking and obfuscation Using R8 in Android
Code shrinking and obfuscation helps you to significantly reduce the size of your application. Enabling shrinking, you benefit from obfuscation, which shortens the names of your app’s classes and members, and optimization, which applies more aggressive strategies to further reduce the size of your app. In android application is used to perform code shrinking, resource shrinking, obfuscation and optimization.
Benefits of code shrinking using R8
- App Size - Application size is greatly reduced by almost up to 65%
- Security - Help rename the app classes making it difficult for reverse engineers to reverse engineer your app.
Enabling Code shrinking
in your build.gradle add this code
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
Then in the proguard-rules.pro is where you declare classes that you need to keep. For instance, when your app makes network requests to an API you have to keep the data classes associated with the data being fetched since if they are renamed by R8 then the app won't be able to understand them in the renamed format. Example of keeping classes in proguard rules.
-keep class com.example.tutorial.models.** { *; }
you can also choose to keep the class directly in the class name by annotating it by @ Keep
@Keep
data class RemoteData(
val name: String,
val type: String,
val date: String
)