APK Size Optimization Techniques: R File, Kotlin Resources, and ShrinkResources
This article details three APK optimization strategies: R file optimization reducing 1MB and 175,692 fields, Kotlin resource optimization saving 447KB, and shrinkResources optimization removing 340KB of unused resources.
This article presents comprehensive APK size optimization techniques for Android applications. The optimization strategies are demonstrated through specific case studies from the 'Xigua' app versions.
1. R File Optimization
The R.java file contains excessive fields (175,692 in version 2.7.0), accounting for 75.5% of total app fields. This bloat stems from Android Gradle Plugin's merge behavior across modules and dependencies on libraries like support v4/v7. The optimization approach uses ASM to replace R field access instructions with constant loads and safely removes R files, as framework code uses resources.arsc instead. Results: 1MB reduction, 175,692 fewer fields, and one fewer dex file (8% improvement).
2. Kotlin Resource Optimization
This section covers optimization of .kotlin_module, .kotlin_builtins, .kotlin_metadata, @Metadata annotations, and Runtime Invisible Annotations. .kotlin_module files (8.8KB saved) are compiler-only resources that can be excluded via packagingOptions. .kotlin_builtins files (11KB saved) are removed when kotlin-reflect isn't used, determined through dependency analysis and bytecode inspection. @Metadata and Runtime Invisible Annotations (427.2KB saved) are removed when not accessed via reflection, using ASM manipulation after ProGuard processing.
3. shrinkResources Optimization
While Android Gradle Plugin's shrinkResources replaces unused resources with empty files, this approach deletes those stripped files entirely. By parsing the resources.txt mapping file and removing unused resources while preserving compression algorithms, an additional 340KB is saved (2% improvement).
4. Summary
Collectively, these optimizations achieve approximately 13% APK size reduction. While not as dramatic as removing entire features, these mechanism-based strategies provide ongoing protection against code bloat and resource accumulation in future development.
Watermelon Video Tech Team
Technical practice sharing from Watermelon Video
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.