APK volume optimization (with Android Studio operating instructions)

table of Contents

1. The meaning of compressing APK volume

2. APK composition and packaging

3. Compression and optimization of res resources

3.1 Delete unreferenced resources

3.2 Use WebP to compress pictures

3.3 Use TinyPNG to compress pictures

4. Delete redundant code (unreferenced classes / methods / variables)

4.1 Code obfuscation

4.2 Use Lint to find useless code

5. Zip format optimization

6. Classes.dex optimization

7. lib optimization

8. References


 

1. The meaning of compressing APK volume

 

  • As the project continues to iterate, more and more functions, the size of the apk file built will also become larger and larger, which will cause the network traffic used when downloading in the case of mobile networks to increase, and the apk is too large , Leading to an increase in download time. Although everyone ’s mobile phones have a lot of traffic and have little effect on user traffic, according to some website statistics, the larger the installation package, the conversion rate of users is decreasing, so the apk is reduced. The volume allows more users to download and experience products; [1]
  • Compressing the APK volume also has a very important significance is to save the memory space and storage space of the mobile phone. After the APK volume is compressed, the resource loading when running the APP is less, the mobile phone memory occupied will be less, and the overall operation is smoother;
  • For some software with rich functions, a multi-plug-in architecture may be used internally, and these plug-ins may also be composed of individual APKs. Then, when the user uses the corresponding function of the plug-in for the first time after downloading the software, that is, when the cold boot If the APK is too large, it will cause slow loading, which will seriously affect the user experience.

 

2. APK composition and packaging

Here is an example of a release version of the APK compiled by Demo, to see what is installed in an APK:

Here is a detailed introduction to the composition of APK: [2]

  • lib: store the so file, there may be armeabi, armeabi-v7a, arm64-v8a, x86, x86_64, mips, in most cases only need to support armabi and x86 architecture, if not necessary, you can consider removing x86 section;
  • res: store compiled resource files, such as drawable, layout, etc .;
  • assets: the resources of the application, the application can use AssetManager to retrieve the resources;
  • META-INF: This folder is generally stored in the signed APK, which contains information such as the signature summary of all files in the APK;
  • kotlin: These files contain data used to declare standard ("built-in") Kotlin classes, which are not compiled into .class files, but are mapped to existing types on the platform (in this case, JVM). For example, kotlin / kotlin.kotlin_builtins contains non-physical information in the kotlin package: Int, String, Enum, Annotation, Collection, etc .;
  • classes (n) .dex: The classes file is a Java Class, a file format that can be understood by Dalvik / ART virtual machine after being compiled by DEX;
  • resources.arsc: compiled binary resource file;
  • AndroidManifest.xml: Android manifest file, the format is AXML, used to describe the four components of the application name, version, required permissions, and registration.

Here is a supplement to the process of App resources being packaged into APKs. The Android build tool chain uses AAPT tools to process resources. Look at the following figure:

 

3. Compression and optimization of res resources

3.1 Delete unreferenced resources

In an Android project, there will be more or less unreferenced resource files. Android Studio has a built-in Lint tool to find invalid resources. The following uses Demo as an example to introduce specific steps:

Step 1: Click Analyze-> Run Inspection by Name ... in the upper menu bar

Step 2: Search for unused resourses

Step 3: Set up and start checking resources

The Lint tool will display a list of resource files that have not been referenced in the project after running, and then you can start removing these files:

3.2 Use WebP to compress pictures

WebP is a picture file format that provides both lossy and lossless compression (reversible compression), derived from the image encoding format VP8, and is considered a sister project of the WebM multimedia format. WebP was originally released by Google in 2010. The goal is to reduce the file size, but to achieve the same picture quality as the JPEG format, hoping to reduce the transmission time of picture files on the network. [3]

According to earlier Google tests, WebP's lossless compression is 45% less file size than PNG files found on the web. Even if these PNG files are processed using pngcrush and PNGOUT, WebP can still reduce the file size by 28%. [4]

Android: Android 4.0 (API level 14) and higher supports lossy WebP images, Android 4.3 (API level 18) and higher supports lossless and transparent WebP images.

IOS: The current iOS does not support webp. I do n’t know if it will be supported in the future, so after getting a webp format picture from the network, it cannot be displayed directly. You need to convert the data data to jpg or png to display.

Let's talk about the webp conversion tool and operation steps built in Android Studio:

Step 1: Right-click the image to be converted and select convert to webp ...

Step 2: Set up and start conversion

3.3 Use TinyPNG to compress pictures

TinyPNG is a free online image lossless compression tool, the compression effect is good, it is recommended to everyone:

 

4. Delete redundant code (unreferenced classes / methods / variables)

4.1 Code obfuscation

Obfuscating the code is not to prevent the code from being decompiled, but to rename the classes, methods, variables, and other information in the code and change them to meaningless names. You can also remove unused classes, Methods, variables, etc. So intuitively, obfuscation can improve the security of the program, increase the difficulty of reverse engineering, and also effectively reduce the size of the apk. The main functions are as follows: [5]

  • Rename the class, method, variable and other information in the project into short meaningless names;
  • Remove unused classes, methods, variables, etc .;

Make the following configuration in the gradle file under the main module of the APP: [1]

buildTypes { 
	release { 
		//开启代码混淆 
		minifyEnabled true 
		//Zipalign优化 
		zipAlignEnabled true 
		//移除无用的resource文件 
		shrinkResources true 
		proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
	} 
} 

Use shrinkResources to remove, but to use shrinkResources, you must first enable code obfuscation minifyEnabled.

In addition to the minifyEnabled attribute, there are proguardFiles attributes for defining ProGuard rules:

  • getDefaultProguardFile(‘proguard-android.txt')The tools/proguard/default ProGuard settings are obtained from the Android SDK folder.
  • proguard-rules.proThe file is used to add custom ProGuard rules. By default, this file is located in the module root directory (next to the build.gradle file).

Note: Code compression will slow down the build speed, so it should be avoided in debug builds whenever possible. However, be sure to enable code compression for the final APK used for testing. If you cannot fully customize the code you want to keep, you may introduce errors.

4.2 Use Lint to find useless code

Using Lint to find unreferenced resources similar to the above, click Analyze-> Analyze-> Run Inspection by Name ...

Search for unused declaration as follows:

The search results will list the unreferenced classes / methods / variables, and then you can consider removing these useless code:

 

5. Zip format optimization

APK details can be viewed via aapt l -v xxx.apk or unzip -l xxx.apk:

The figure can be seen by a lot of resources in the APK is Storedto store these files are not compressed. Find the following description from the AAPT source code:

/* these formats are already compressed, or don't compress well */
static const char* kNoCompressExt[] = {
    ".jpg", ".jpeg", ".png", ".gif",
    ".wav", ".mp2", ".mp3", ".ogg", ".aac",
    ".mpg", ".mpeg", ".mid", ".midi", ".smf", ".jet",
    ".rtttl", ".imy", ".xmf", ".mp4", ".m4a",
    ".m4v", ".3gp", ".3gpp", ".3g2", ".3gpp2",
    ".amr", ".awb", ".wma", ".wmv", ".webm", ".mkv"
};

It can be seen that AAPT does not compress the resources of these file suffix types during resource processing. Is it possible to modify their compression method to achieve the effect of slimming? The detailed compression method can be referred to: Meituan technical team-Android App package slimming optimization practice

 

6. Classes.dex optimization

How to optimize the size of classes.dex generally has the following two directions: [2]

  • Maintain good programming habits and a keen sense of package size at all times, remove duplicate or unused code, use third-party libraries with caution, choose small third-party SDKs, etc.
  • Turn on ProGuard for code compression, and use ProGuard to obfuscate, optimize, and compress code.

 

7. lib optimization

When developing Android applications, you often use external library libraries to improve the usability and scalability of your app. For example, you will introduce the Android Support Library to enhance the user experience on older models, or you will use Google Play Service to automatically translate the text in your app. If a library is designed as a service or desktop, then it will contain many objects and methods that are not used by your application. In order to include only the parts used in your project, you can modify this library file. If the license permits, you can also use another mobile-friendly library to add specific functions to your app. [6]

Note: Progard can clear some useless code in the imported library, but it cannot clear large internal dependencies in the library.

There is an open source solution on GitHub-upx: https://github.com/upx/upx

Introduction of upx (50% ~ 70% compression ratio):

UPX is an advanced executable file compressor. UPX will typically
reduce the file size of programs and DLLs by around 50%-70%, thus
reducing disk space, network load times, download times and
other distribution and storage costs.

Programs and libraries compressed by UPX are completely self-contained
and run exactly as before, with no runtime or memory penalty for most
of the supported formats.

 

8. References

[1] Zhihu-Column-Andriod APK Volume Optimization

[2] Meituan technical team-Android App package slimming optimization practice

[3] Wikipedia-WebP

[4] Baidu Encyclopedia-webp format

[5] Nuggets-Detailed explanation of Android code obfuscation

[6] Brief Book-Performance Optimization (6)-Reduce APK Volume

Published 16 original articles · praised 59 · 10,000+ views

Guess you like

Origin blog.csdn.net/Carson1145/article/details/105609608