Andorid performance optimization (4) How to slim down Apk

1 Introduction

In our daily development process, with the iteration of the version, the increase of application modules or functions, the redundancy of old codes, the addition of various cool effects, the requirements of large-resolution mobile phones for pictures, the unreasonable use of pictures, and abuse of third parties Library, and other reasons, the Apk file of the application installation package has gradually become larger and larger. Although the current mobile phone traffic price is not as high as in the past few years and the WiFi coverage environment is more and more, the mobile phone performance and storage space are not as harsh as in the past, and it is not a big problem to increase the installation package by a few M These are not reasons why we can ignore this problem. Think about an ordinary function application if the installation package is too large, it will affect the user's choice compared with competing products and is at a disadvantage; the package will also be proportional to the download time, installation time and occupation time, and if it is because of the code Large amounts, large pictures, and large numbers of images can also cause the memory usage of the application itself. So the size of a few M that looks painless and itchy, in fact, these are also an optimization that the product experience should pursue. In this article today, let ’s take a look at the situations and solutions that cause the application installation package to become larger.

2 Where to start

The Apk file is actually a zip package, so we can view the internal file structure. Generally, the structure of an Apk package is shown in the following figure.

It mainly contains the following files:

assets                            contains some non-compilable resource files such as db database files, font libraries, Json / Xml configuration, etc.

                                  SO files of different ABI types that lib depends on

res                                  XML, pictures, audio, etc. compiled resource files

classes.dex                   contains the compiled class files of the written Java code, one or more, depending on whether the number of methods exceeds 65525

Resource.arsc             compiled resource mapping relationship configuration information, equivalent to resource index table

META-INF                      stores signature related information

AndroidManifest.xml is   used to configure the manifest file of App information and four component information

Therefore, we want to slim down Apk. In fact, in a very simple sentence, we should start with Java source code and resource files, delete code and resources, refactor code and resources, and compress code and resources.

3 slimming program

3.1 Reduce code size

The code in an application can be simple and simple, the amount of code will not affect the size of the installation package, and it will also cause the application to occupy a high memory (this argument is described in the previous article "Andorid performance optimization (1) how to optimize memory for the application". See PSS Ever). Reducing the amount of code can start from the following aspects:

Cut function

The cut function is the most direct way to reduce the amount of code. Face up to user data, functions that do n’t work well, functions that do n’t hurt or itch can be chopped, and it ’s better to use an app more than functions.

Remove old code

If you do n’t want to remove the functions you do n’t want, you can use the code version management tool to retrieve them later, or make a backup before removing them.

Avoid misuse of third-party libraries

The third-party library is easy and fast to use, but it is also a double-edged knife. Some simple logic can be developed by yourself, and you should try to rely on libraries written by others as little as possible. And sometimes it is often because of wanting to use a little logic to refer to a heavyweight library, which is not a loss.

Common code extraction

Cultivate the habit of refactoring code after functional development. Reuse public code as much as possible to reduce code redundancy. Writing beautiful code should be the goal that every developer has always pursued.

Use Android Lint tool

Use the Android Lint tool to delete unused code, including imports, variables, methods and classes, etc. We will introduce the use of Android Lint below.

3.2 Organize resources

Resources are the most direct cause of high memory usage of applications and larger installation packages, so we must face the rational use of resources. Let's take a look at how to organize resources:

Compress resource pictures

Compressing pictures is the most immediate method. Currently, it is more popular to use https://tinypng.com to compress pictures, and the effect is still very good. Moreover, it must be pressed all the time, repeatedly, until the human eye can see the distortion before it stops.

Use as few pictures as possible

Sometimes, we may only need relatively simple gradient colors or graphics in our needs. Then, instead of using Bitmap, it is possible to use the Drawable provided by Android. Drawable is often used as the background of the View. It is generally defined through XML. Or it can be drawn through the onDraw of the self-defined View. This is to save both memory and space. Sometimes when you have to use a picture, you must first consider whether you can use a picture with the smallest size or use a .9 picture.

Picture reuse

If you only have pictures with different directions, you can use only one, and then use RotateDrawable to rotate, such as: 

Use Android Lint tool

Using the Android Lint tool can also find useless, duplicate resources, such as: string, color, drawable, etc. We will introduce the use of Android Lint below.

Simplify the picture effect

The more the color of a picture, the larger the picture file. Within the acceptable range, you can simplify some picture effects slightly, such as removing some edge glow and gradient effects.

Try to use non-transparent images

Pictures with a transparent effect are larger than non-transparent pictures because they have a transparent channel. If the background color is not clear and there are many different background uses, you can consider directly filling the background color without making it transparent.

Frame animation transformation

The following picture is the chrysanthemum animation used for waiting. It was originally implemented using frame animation, but this requires 16 pictures:

In fact, the same effect can be changed to attribute animation + fan mask to achieve. In this way, 14 pictures can be saved, and the space that can be saved may be 10 times:

Picture mosaic multiplexing

Pictures can also be reused like code, using the stitching method, in addition to reducing the use of large pictures, but also conducive to later expansion, like the following:

Clouding of some resources

Like some libraries and configurations that are not used for the first time, you can consider filtering to cloudize them, and then find the right time to pull them down.

Make good use of font library

Some commonly used monochrome icons can be considered to be converted into vector graphics and provided in the form of font libraries.

3.3 Packing and Compression

Slimming through Gradle

minifyEnable

Gradle provides a code obfuscation mechanism, use minifyEnable = true to enable it. Code obfuscation is a very useful function. It not only makes the size of the Apk package smaller, but also makes it difficult for people who decompile to understand our source code logic to increase the difficulty of analysis. Generally, the version compiled in release mode will start the obfuscation function.

shrinkResources

Gradle provides a configuration to automatically clean up unused resources and enable shrinkResources = true . This configuration should be used in conjunction with minifyEnable, because after the useless code is cleaned up, the resources referenced by some useless code can be cleaned up.

The same problem exists when using minifyEnable and shrinkResources , that is, when reflection is used in the code, Android Gradle can't distinguish it, so that the target class code cannot be reflected and the referenced resources are cleaned up by mistake, so it is used in Pay attention to configure the keep whitelist.

resConfigs

ResConfigs in Gradle belongs to a method of PraductFlavor {}, which allows us to configure which types of resources are hit into the package.

For more information about Gradle, please refer to the previous Gradle series article "Detailed Explanation of Android Gradle Usage (3) Detailed Explanation of Android Gradle Plugin Configuration" .

AndResGuard confuses resources

AndResGuard is a resource confusion packaging tool. By modifying the resources.arsc file, it can obfuscate the resource file path of the Apk package (such as confusing res / drawable / welcome.png to r / s / a.png), and can also achieve the purpose of reducing the size of the Apk package. Its use is very simple, and it needs to be configured in Gradle. For detailed steps, please refer to the previous Gradle series article "Android Gradle Detailed Use (8) Using AndResGuard to Obfuscate Apk Package Resources" .

3.4 Pluginization

It is not the first time in the application that it is used as an independent module function. You can consider plugging it in. For related knowledge about plugging, you can refer to the previous plugging series article "Principle and Practice of Android Plugging" .

4 Steps to use Android Lint to slim down the app

Android Lint is a static code detection tool provided by the Android SDK. Its source code is integrated in Android SDK Tools 16 and higher. We can call it through the ./gradlew lint command in the project directory, or we can call Lint inspection through the [Analyze]-> [Inspect Code] path of Android Studio. It can help us to check the problems in the project and allow us to develop apps in a more standardized way. The problems it detects are, for example:

  1. Layout performance, such as: useless layout, too much nesting, too many layouts
  2. Internationalization issues, is there hard coding in the xml file
  3. Unused resources and codes
  4. Inconsistent array size
  5. Icon problems, such as: duplicate icons, wrong size
  6. Usability issues
  7. Possible bug
  8. and many more

The author here generates a test report by using lint in a project, as shown below. In terms of applying weight loss, we only need to focus on the following five major issues for the time being:

Question 1: After Android> Lint> Performance is expanded, there is an Unused resources item, which represents useless resources, including pictures, XML, string, colors, style, etc.

Question 2: There are two items in Android> Lint> Usability> Icons after expansion: Duplicated icons under different names and Identical bitmaps across various configurations . They represent different names, but the same picture (MD5 is exactly the same picture, but there are multiple pictures) and different specifications use two same pictures (for example: the same picture is used in hdpi and xhdpi).

Question 3: Declaration> redundancy has two items after expansion: Empty method and Unused declaration. They represent empty methods and unused declarations respectively, including variables, methods, and classes.

Question 4: After the Imports are expanded, there is an Unused import item, which means useless imports.

           

Question 5: After the XML is expanded, there is an Unused XML schema declaration item, which indicates an unused XML schema declaration.

The five major problems listed above, we can generally see the effect of weight loss after we solve it as much as possible. In particular, it is better to run Android Lint repeatedly to detect it several times, because if you delete the useless code and then detect it, it may detect the resources associated with it.

 

 

Published 106 original articles · praised 37 · 80,000 views

Guess you like

Origin blog.csdn.net/lyz_zyx/article/details/85841675