The latest version of the Android Gradle Plugin (AGP) introduces an optimized resource-shrinking approach that unifies code optimization and resource shrinking, achieving up to 50% reduction in app size for apps that share significant resources and code across different form factor, says Google.
In the new approach, Android’s long-standing optimizer R8, processes code and resource references at the same time, which makes it possible to identify all resources that are only referenced from unused code, and thus remove them along with the unused code.
This completely eliminates the need for the unconditional keep rules generated by AAPT2 (the resource packaging tool for Android) and provides much more fine-grained and precise information for discarding unused code and resources.
In previous versions, AAPT2 generated unconditional keep rules before R8 optimized the code, often causing them to reference unused code and preventing R8 from removing that code along with its associated resources.
“As mentioned, the new R8 optimization pipeline can achieve over 50% improvements in apps that share significant code and resources across different form factors, while also providing measurable benefits for smaller apps.
With the new optimized behavior, developers now have four distinct approaches to app optimization: no optimization, R8-only, R8 with resource shrinking, and optimized resource shrinking. Each successive step provides additional benefits.
Enabling R8 trims the size of your DEX, while enabling resource shrinking removes unused resources in both the res folder and in the resource table, but does not change the DEX size further, and finally, optimized resource shrinking further reduces the size by removing both resources and DEX code since it can trace references across the DEX and resource boundary
The new resource shrinking pipeline is available as an opt-in in the latest AGP 8.12.0. To enable it, you use the following AGP configuration:
android {
buildTypes {
release {
isMinifyEnabled = true
isShrinkResources = true
…
}
}
}
The new behavior will be the default in the upcoming AGP 9.
Reducing an app’s size has several benefits, including faster download, quicker installation, and lower memory consumption. It also improves startup time, enhances rendering speed, and reduces ANRs (Application Not Responding behavior usually occurring when an app’s UI thread is blocked for too long).