4.2. Android Studio compresses your code and resources

In order to make your APK file as small as possible, you need to turn on compression when building to remove useless code and resources.

Code compression can be used in ProGuard, you can detect and clear useless classes, variables, methods and properties, and even libraries you reference. ProGuard can also optimize bytecode, remove useless code, and obscure the remaining classes, variables, and methods. Fuzzy code can increase the cost of APK reverse engineering.

Resource compression can be used in Andorid's Gradle plugin, which can clear useless resources in your packaged APP, including useless resources in libraries you reference.

Compress your code
in order to enable ProGuard code compression, you need to add minifyEnabled true in build.gradle in.

It should be noted that code compression will slow down the build speed, so if possible, try to avoid using it in debug builds.

as follows:

android {
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile(‘proguard-android.txt'),
                    'proguard-rules.pro'
        }
    }
    ...
}

Note: Android Studio will disable ProGuard when using Instant Run.

What are custom code needs to retain
in many cases, ProGuard is difficult to analyze correctly, it may need to clear your app code.
1. When your app references a class from AndroidManifest.xml
2. When your app calls a JNI method
3. When your app uses reflection to control the code

In order to avoid this problem, you need to use -keep, as follows:
-keep public class MyClass

Similarly, you can add @Keep annotation to achieve.

Compress your resource
resource compression needs to be compressed together with the code to work properly. After the code has compressed out all the useless codes, it can be distinguished which resources are still unused. as follows:

android {
    ...
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
                    'proguard-rules.pro'
        }
    }
}

Customize what resources need to be retained
if there some special resources you need to keep or discard, create an XML file containing tags in your project, use tools: Resource keep specify the need to keep, using tools: discard indicate the need to discard documents .
such as:

<?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" />

Author: Song Zhihui
personal micro-blog: Click to enter

Guess you like

Origin blog.csdn.net/song19891121/article/details/51774077