Android Performance Optimizer series APK slimming

Source: Internet
Author: User
Tags webp tinypng

Optimization of the Android performance optimization series

Memory optimization in the Android performance optimization series

Why the APK wants to lose weight. The larger the APK, the more traffic they will consume during the download installation process, the longer the installation wait time, and the lower the download conversion rate for the product itself (because the user has more opportunities to choose the best, most functional, best performance and smallest package), so it is also important to optimize the APK's slimming This blog will tell you about APK slimming.

Package Body Analysis

In the Android Studio toolbar, open the Build–>analyze apk and select the APK package to analyze.

You can see the main footprint of the code, pictures, resources and Lib and assert files, the main direction to streamline the code, Compress pictures, remove useless libraries, reduce asserts inside the file.

use a set of resources

For a great log app, it's enough to just take a set of design drawings. Given the current resolution trend, it is recommended to take 720p resources and put them into the xhdpi directory.
Compared to multiple sets of resources, only use 720P of a set of resources, in the visual difference is not small, many large companies of the product is the same, but can significantly reduce the size of resources, the way can also alleviate the designer's drawing workload.
Note that this is not to say that directories that are not xhdpi are deleted, but that it is sufficient to keep a set of design resources.

turn on minifyenabled obfuscation code

The Gradle uses minifyenabled for proguard confusing configuration, which greatly reduces the size of the app:

android {    buildTypes {        release {            true        }    }}

In Proguard, the preservation of the symbol table has a significant effect on the size of the app and is not retained as appropriate, but it is recommended that you try to keep it for debugging.

Parameters:

-include {filename}    从给定的文件中读取配置参数   -basedirectory {directoryname}    指定基础目录为以后相对的档案名称   -injars {class_path}    指定要处理的应用程序jar,war,ear和目录   -outjars {class_path}    指定处理完后要输出的jar,war,ear和目录的名称   -libraryjars {classpath}    指定要处理的应用程序jar,war,ear和目录所需要的程序库文件   -dontskipnonpubliclibraryclasses    指定不去忽略非公共的库类。   -dontskipnonpubliclibraryclassmembers    指定不去忽略包可见的库类的成员。

Retention options

-keep {Modifier} {class_specification}    保护指定的类文件和类的成员   -keepclassmembers {modifier} {class_specification}    保护指定类的成员,如果此类受到保护他们会保护的更好   -keepclasseswithmembers {class_specification}    保护指定的类和类的成员,但条件是所有指定的类和类成员是要存在。   -keepnames {class_specification}    保护指定的类和类的成员的名称(如果他们不会压缩步骤中删除)   -keepclassmembernames {class_specification}    保护指定的类的成员的名称(如果他们不会压缩步骤中删除)   -keepclasseswithmembernames {class_specification}    保护指定的类和类的成员的名称,如果所有指定的类成员出席(在压缩步骤之后)   -printseeds {filename}    列出类和类的成员-keep选项的清单,标准输出到给定的文件  

Compression

-dontshrink    不压缩输入的类文件   -printusage {filename}   -whyareyoukeeping {class_specification}  

Optimization

-dontoptimize    不优化输入的类文件   -assumenosideeffects {class_specification}    优化时假设指定的方法,没有任何副作用   -allowaccessmodification    优化时允许访问并修改有修饰符的类和类的成员  

Confuse

-Dontobfuscate does not confuse the input class file-printmapping {filename}-applymapping {filename} reuse mappings Add confusion-obfuscationdictionary {filename} uses the keyword in the given file as the name of the method to be confused-overloadaggressively obfuscation when applying intrusive overloads-Useuniqueclassmembernames Determining the member names of a unified obfuscation class to increase confusion-flattenpackagehierarchy {package_name} repack all renamed packages and place them in a given single package-repackageclass {package_name} repack all renamed class files in a given single package-Dontusemixedcaseclassnames Confusion does not produce a variety of class names-keepattributes {attribute_name,...} Protects a given optional attribute, such as linenumbertable, localvariabletable, sourcefile, Deprecated,   Synthetic, Signature,  and innerclasses. -Renamesourcefileattribute {String} sets the given string constant in the source file
turn on shrinkresources to remove useless resources

The Gradle uses shrinkresources to remove useless resources, which works very well.

android {    buildTypes {        release {            true        }    }}
clean up Useless resources

During the iteration of the version, not only are there redundant code redundancy, there will definitely be useless images. In the Build.gradle configuration shrinkresources True, in the packaging will automatically remove the useless resources, but after the experiment found that the package does not, but will be part of the useless resources with smaller things instead. Note that the "useless" here means that all the parent functions that call the picture end up being discarded code, and shrinkresources True can only be removed without any parent function calls, and the real effect can only be achieved through the "remove Unused" that comes with Android studio. Resources "Small plug-ins to achieve, directly.

More humane is that the search results can be "one-click Delete." Of course, maybe the picture is through reflection or character stitching, and so on, so this detection list is not all right, after the deletion of a large probability of compilation failure or part of the page hanging dead, no diagram and other problems, this no solution, the tool has not been intelligent to this point, you can only over and over again "compile-solve part of the problem- "Don't ask me why I know."

Remove useless language resources

Most applications do not need to support internationalization support in dozens of languages. Fortunately strong Gradle support language configuration, such as domestic applications only support Chinese:

android {    defaultConfig {        "zh"    }}
using tinypng lossy compression

Tinypng tool only supports uploading PNG images to official web compression, and then download and save, in the case of maintaining the alpha channel to the PNG compression can reach 1/3, and with the naked eye basically cannot distinguish the loss of compression.
Tinypng's official website: http://tinypng.com/

use JPG format

If the larger image is opaque, the JPG will have a significant advantage over the size of PNG, though not absolute, but will usually be reduced to half.
In the Start page, the active page, and so on the large image display area with JPG will be very wise choice.

using the WEBP format

WEBP support transparency, compression compared to JPG higher but the display effect is not lost in JPG, the official evaluation quality parameter equals 75 balance best.
Relative to JPG, png,webp as a new image format, limited to the support of Android is not used in the mobile phone for a wide range of applications. Native support starts from Android 4.0+, but does not support the inclusion of transparency until Android 4.2.1+ supports the display of WEBP with transparency, especially when used.
Official Introduction: https://developers.google.com/speed/webp/docs/precompiled

Zoom out big picture

If after the above steps, there are some large drawings in your project, consider whether it is necessary to maintain such a large size, whether the appropriate reduction.
In fact, because of the designers out of the picture, we get a lot of pictures can be properly narrowed and the visual impact is very small.

overlay The big picture in the third library

Some of the third libraries cite some large images but are not actually used by us, so we can consider using 1x1 transparent images to cover them.
You might be a little uncomfortable, because your drawable under a 1x1 picture that contains some inexplicable names ...

Delete the so under the ARMABLE-V7 package

Basically armable so is compatible with ARMABLE-V7, ARMABLE-V7A Library will have a great improvement on graphics rendering, if there is no such requirements, can be streamlined.
Here does not rule out a very small number of equipment will be crash, May and different so have a certain relationship, please be sure to test thoroughly before release.

Delete the so under the x86 package

Unlike the tenth, the x86 bag is needed for the x86 model, and can be streamlined if the product doesn't work.
Recommended that the actual work is configured to keep only armable, armable-x86 under the so file, is considered a compromise solution.

using the Resource compression packaging tool

Resource Compression packaging tool through the short resource name, the use of 7zip to the extreme compression of the app to reduce the target of the app, the effect is very good, highly recommended.

Recommended to open 7zip, pay attention to the white list configuration, otherwise it will cause some resources can not find, the official has released Andresguard to Gradle, very convenient:

Apply plugin:' Andresguard 'Buildscript {dependencies {classpath' com.tencent.mm:andresguard-gradle-plugin:1.1.7 '}}andresguard {mappingfile =NULLUse7zip =trueUsesign =trueKeeproot =false    //Add <your_application_id>. R.drawable.icon into whitelist.    //Because the launcher would get Thgge icon with his name    defPackageName = <your_application_id> WhiteList = [//for your iconPackageName +". R.drawable.icon ",//for FabricPackageName +". r.string.com.crashlytics.*",//for umeng UpdatePackageName +". r.string.umeng* ", PackageName +". r.string.um* ", PackageName +". R.string.tb_* ", PackageName +". r.layout.umeng* ", PackageName +". R.layout.tb_* ", PackageName +". r.drawable.umeng* ", PackageName +". R.drawable.tb_* ", PackageName +". r.anim.umeng* ", PackageName +". r.color.umeng* ", PackageName +". R.color.tb_* ", PackageName +". r.style.*um* ", PackageName +". r.style.umeng* ", PackageName +". r.id.umeng* "] Compressfilepattern = ["*.png","*.jpg","*.jpeg","*.gif","RESOURCES.ARSC"] Sevenzip {artifact =' com.tencent.mm:sevenzip:1.1.7 '        //path = "/usr/local/bin/7za"}}

Generates a Andresguard/resguard task that automatically reads the release signature for re-obfuscation packaging.

compiling with provided

For some libraries are dynamically loaded as needed, it may not be necessary in some versions, but the code is not easy to remove otherwise it will compile.
The use of provided can guarantee code compilation, but the actual packaging does not refer to this third-party library, achieving the goal of controlling the size of the app.
But at the same time it is necessary for developers to decide not to refer to the third-party library when they do not implement the relevant code, to avoid the app crashes.

Vector Diagram

Vector graphics are composed of dots and lines, and bitmaps are not the same, it can also be enlarged to maintain clarity, and using vector graphics than bitmap design can save 30~40% space, now Google has been emphasizing the flat way, vector diagram can be very good fit the design concept.
-Advantages
(1) Small storage footprint
(2) The infinite stretch will not appear sawtooth, can take care of different sizes of models
(3) Android Studio comes with a lot of resources to reduce UI effort
-Disadvantage
(1) Only support 5.0 and above system
(2) One more layer of computation compared to bitmaps, which consumes more performance
(3) not supported. 9 Figure
(4) Not suitable for real photos and complex graphics, generally used in simple icon and animation

using the shape background

Especially in the current of flattening, a lot of solid color gradient rounded pictures can be achieved with shape, the code is flexible and controllable, eliminating a lot of background images.

using the shading scheme

I believe your project also has a lot of selector files, there are many similar pictures just different colors, through the coloring scheme we can greatly reduce such a workload, reduce such files.
Use the Android support library to implement a full version compatible coloring scheme, reference code: Drawableless.java

Online Library of Materials

If your app supports libraries (such as chat emoticons), consider loading patterns online because the library has a large volume.
This step requires developers to implement online loading, on the one hand to increase the complexity of the code, on the one hand to improve the app's traffic consumption, recommended as a discretionary choice.

Avoid duplicate libraries

Avoid repeating the library seems to be taken for granted, but the secret is always deep, be aware of the third-party library you refer to which third-party library, it is easy to have a duplicate library, such as the use of two images loaded library: Glide and Picasso.
Try to avoid duplicating the size of the library and reducing the size of the app by looking at the Exploded-aar directory and external libraries or decompile the generated apk.

Clean up third-party libraries and redundant code

Version iteration process, because the deletion function often has redundant code and third-party library left, this will more or less add the package body, this situation there is no shortcut, only each file lookup, this is the drudgery. Also want to see third-party library there is no possibility of streamlining, such as the Google sub-Foundation, advertising and analysis package, network library, SUPPORTV4, etc., this specific situation specific analysis, not much elaboration.

plug-in support

Plug-in technology supports dynamic loading code and dynamic loading resources, separating part of the app, which is very useful for large business projects, and greatly decomposes the size of the app.
Because plug-in technology needs a certain degree of technical assurance and service-side system support, there is a certain risk, if not necessary (such as some small projects, there is no expansion of the business) is not necessary, the recommended choice.

Facebook's Redex optimized byte code

Redex is an optimization tool for Android bytecode released by Facebook and needs to be configured in its own documentation.

redex input.-o output.---s<KEYSTORE>-a<KEYALIAS>-p<KEYPASS>

Let's take a look at its effect, with only redex, reducing the 157k:

Let's take a look at its effect, with only redex, reducing the 157k:

If the first confusion, then Redex, reduced the 565k,redex only contributed 10k:

If the redex is first performed, the 711k,redex contributed 157k in the confusion, reduced:

The final effect is the best, it is easy to explain, if the final redex re-packaging is wasteful of the front 7zip compression, so in order to optimize the effect of attention to order.
In addition, according to the reaction Redex after the phenomenon of collapse, this should pay attention to, I here after compression can be normal operation.
Detailed reference: Redex

Android Performance Optimizer series APK slimming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.