ProGuard and R8 help make your Android app smaller and faster by removing unused code and optimizing what remains.
ProGuard and R8 optimization in Android Kotlin
android {
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}minifyEnabled true turns on code shrinking and optimization.
proguardFiles lists the configuration files for rules to keep or remove code.
minifyEnabled false
minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'my-proguard-rules.pro'
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}This example shows a simple Android app with ProGuard and R8 enabled for release builds. The ProGuard rules keep the main activity so it is not removed. When you build the release version, unused code is removed and the app size is smaller.
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
namespace 'com.example.proguarddemo'
compileSdk 33
defaultConfig {
applicationId 'com.example.proguarddemo'
minSdk 21
targetSdk 33
versionCode 1
versionName '1.0'
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
// proguard-rules.pro
# Keep MainActivity class
-keep class com.example.proguarddemo.MainActivity { *; }
// MainActivity.kt
package com.example.proguarddemo
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.TextView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val textView = TextView(this)
textView.text = "Hello ProGuard and R8!"
setContentView(textView)
}
}R8 is the default code shrinker and optimizer in Android Studio now, replacing ProGuard but still using ProGuard rules.
Always test your app after enabling minify to make sure important code is not removed.
You can add custom rules in proguard-rules.pro to keep code needed by reflection or libraries.
ProGuard and R8 help shrink and optimize your Android app code.
Enable minifyEnabled true in release build to activate them.
Use ProGuard rules files to control what code to keep or remove.