To keep your apk files as small as possible, you need to turn on compression at build time to remove useless code and resources.
Code compression can be used in Proguard to detect and purge useless classes, variables, methods, and properties, even including the libraries you reference. Proguard can also optimize bytecode, remove useless code, and blur the rest of the classes, variables, and methods. Code blur can increase the cost of APK reverse engineering.
Resource compression can be used in Andorid's Gradle plug-in to clean up useless resources in your packaged app, including useless resources in the libraries you reference.
Compress your code
In order to enable Proguard code compression, you need to add minifyenabled true in Build.gradle.
It is important to note that code compression slows down the build speed, so if possible, try to avoid using debug builds.
As follows:
android { buildTypes { release { true proguardFiles getDefaultProguardFile(‘proguard-android.txt‘), ‘proguard-rules.pro‘ } } ...}
Note: Android studio disables Proguard when using instant run.
Customize which code needs to be preserved
In many cases, Proguard is difficult to analyze correctly, and it may erase the code that your app needs.
1. When your app refers to a class from a androidmanifest.xml
2. When your app calls a Jni method
3. When your app uses reflection to control code
To avoid this problem, you need to use-keep, as follows:
-keep public class MyClass
Similarly, you can add @keep annotations to implement them.
Compress your resources
Resource compression needs to be combined with code compression for normal use. After the code compresses all of the useless code, you can tell which resources are still unused. As follows:
android { ... buildTypes { release { shrinkResources true minifyEnabled true proguardFiles getDefaultProguardFile(‘proguard-android.txt‘), ‘proguard-rules.pro‘ } }}
Customize which resources need to be retained
If there are some special resources you need to keep or discard, create an XML file with tags in your project, use Tools:keep to indicate which resources you need to keep, and Tools:discard to indicate which files need to be discarded.
Like what:
<?xml version=1.0" encoding="utf-8"?><resources xmlns:tools="http://schemas.android.com/tools" tools:keep="@layout/l_used*_c,@layout/l_used_a,@layout/l_used_b*" tools:discard="@layout/unused2" />
This article Song Zhihui
Personal Weibo: Click to enter
4.2. Android Studio compresses your code and resources