Daniel took a year: in-depth exploration of the Android package volume optimization, on a total of 30,000 words recommended collection

As the article particularly long, it is recommended to collection and re-read.

Among Android performance optimization of knowledge, optimization package volume has been ranked in priority relatively low position, leading many students to develop their own applications do not pay attention to size. In the course of development of the project, it can be generally divided into the following three stages:
start-up => growing => mature
Generally, when the application is in the later stage of the growth period, the volume of the package will consider systems do optimization, therefore, only at this stage and after package volume optimization benefits brought about is considerable.

So, what package size optimization can bring benefits to us? How comprehensive package for the volume of applications systems analysis and targeted optimization it? In this article, we will conduct in-depth analysis and exploration together.

1, thin optimization and analysis program introduced Apk
1, weight-loss advantage

We start with a look at why we need to do weight-loss APK optimization?

There are three reasons:

(1) download conversion rate

  • APK thin optimization in the actual project priority is relatively low, because after doing its benefits are not so obvious, especially those who have not yet stable phase of the project, we all know, development App is from the project early = > growing => stable, for in the early growth stage of development and projects, might do start to optimize, optimize Caton, but generally do not do weight-loss optimization, optimization of the most important benefits of weight-loss application download conversion rate impact, it is an important indicator of business operations App, refined operation at the project stage is very important.

  • Because if your App Apk volume to be smaller compared with other same type of App, then your App download rate may be higher. Moreover, the smaller package size, the download waiting time will be shorter, so the download success rate of the higher conversion. Therefore, the relationship between the size of the installation package to download conversion is substantially inversely proportional, i.e. the greater the installation package, smaller download conversion rate.

  • A 80MB application, even if a user downloaded a point, may also be because the network is slow, suddenly go back on the download fails. For after a 20MB application, the user points the download, do not hesitate to be at the time may have been downloaded over.

  • And now many large App will generally have a Lite version of App, this is for reasons of download conversion rate.

2 application market

  • Google Play app market mandatory application can use more than 100MB of APK expansion files upload. When using APK expansion files upload, Google Play will be managed extensions for our application file, and provided free of charge to the device.

  • Extended file will be saved to a shared storage location of the device (SD card or USB-mountable partition; also referred to as "external" memory), in which the application can access them. On most devices, Google Play will download expansion files downloaded APK same time, so the first time a user opens the application will have everything you need.

  • However, in some cases, our application must download files from Google Play when the application starts. If you want to avoid using file extensions, and you want to download the application size is larger than 100 MB, you should use the Android App Bundles upload your application, then the application can provide up to 150 MB of compressed download size.

  • Android App Bundles is the Android application bundle, which allows App to add dynamic functional modules way to solve the larger problem APK size. Below, it is Android App Bundle APK by a dynamic basic module and two functional modules of FIG composition structure:

3, channel partners requirements

  • In addition, there is a reason, after our App bigger, you may need to cooperate with the various mobile phone manufacturers pre-installed, these channel partners Chamber of Commerce App for your detailed requirements, and only after you meet the corresponding requirements of App allows pre attached to the phone. Moreover, the greater the App its unit cost will be higher. So, after a big weight loss problem it is also a certain experience of our project.

  • Effect on the volume is too large performance App
    Further, in addition to affect the volume of the package to download an application other than the conversion rate, there will be some major impact on the performance of the three aspects of App, as follows:

1) Installation Time: such as file copying, Library decompressed and, at compile time ODEX, especially for Android 5.0 and 6.0 systems, relatively long time-consuming, and with mixing after compiling Android 7.0, it is also acceptable . Finally, the App becomes large, the signature verification time increases.

2) run-time memory: Resource resources, Library and Dex class loader will occupy part of the memory applications.

3) ROM space: If the application installation package size is 50MB, then after starting the decompression is likely to have exceeded the 100MB. And, if the flash memory space is insufficient, the case is likely to "write amplification" appears, it is flash memory and solid state disk (SSD) in a bad phenomenon, flash memory must be erased before it can be re-writing data, erasing granularity and write operations much lower than the operation, these operations will move several times (or rewriting) user data and metadata.

Accordingly, the data to be overwritten, it is necessary to read certain portions of the flash memory has been used, update them, and written to a new position if the new position has been used before, together with the need to erase; because this flash kinds of work, rewrite the flash memory must be erased much larger part than the new data actually needed. That could eventually lead to the amount of data actually written to the physical quantity of data is written to many times.

2, APK composition

As we all know, Android will eventually be compiled into a project .apk file suffix, in fact it is a compressed package. Thus, within it there are many different types of documents, which, according to size, is divided into the following categories:

1) Code related: classes.dex, we in the project prepared by the java files, compiled after a .class file is generated, and these all .class file it, it will eventually go through dx tool to generate a compilation classes.dex .

2) resource-related: res, assets, compiled binary resource files resources.arsc and list of documents and so on. Res and in that different assets res files in directory will generate a corresponding resource ID in the file .R, but does not automatically generate the corresponding assets ID, but is acquired by the interface AssetManager class. In addition, whenever a file decentralization in the res folder, aapt will automatically generate the corresponding id and saved in the .R file, but .R file just to ensure that the compiler does not complain, in fact, the application is running, the system according to find the resources corresponding to the path ID, rather resources.arsc file is used to record the file and the resource file ID of positional correspondence.

3) So Related: file in the lib directory, optimized space this document is actually very large.

In addition, META-INF, which store the signature information applications, of which there are three files, as follows:

MANIFEST.MF: wherein each file has a corresponding resource SHA256-Digest (SHA1) signature, SHA256 MANIFEST.MF file (SHAl) through CERT.SF result is the base64 encoding of the SHA256 (SHA1) - Digest-Manifest value.

CERT.SF: addition (SHA1) -Digest-Manifest SHA256 value defined at the beginning, the value is a value of the back several MANIFEST.MF file again each SHA256 (SHAl) after base64 encoding.

CERT.RSA: contains information on public key encryption algorithm. First, the previous step MANIFEST.MF generated using SHA256 (SHA1) -RSA algorithm, with private developers signature. Then, using the public key decrypted at installation. Finally, it is compared with the unencrypted summary information (MANIFEST.MF file). If they match, it indicates that the contents have not been modified.

Weight-loss program to explore the code

Before explaining how to optimize Dex, Dex may have a lot of students do not have enough understanding of where we first understand in detail under Dex.

1, Dex Quest
1) Dex Android system executable file, the entire operation instruction comprising application and runtime data. Because Dalvik is a device specifically designed for embedded Java virtual machine, so the Dex files with standard Class files are essentially different in structural design.

2) When a Java program is compiled into class files, you need to use the dx tool to integrate all the class files to a dex file so dex file will file the original of each class has a total synthesis of information integration, so the aim is to ensure that each class which are able to share data, which reduces redundancy in a certain extent, but also makes the document more compact.

Compared with the traditional jar file, the file size Dex can reduce about 50%. FIG comparison results on file with Dex Class files is as follows:

If you want in-depth understanding of Dex file format, you can see Google's official tutorial - Dex format.

Dex in the application package typically occupy a lot of volume proportion, and the greater the number of Dex, the App installation time will be longer. Therefore, they can be said to optimize the most important. Here, we look at ways in which to optimize this part of the volume Dex.

2, ProGuard
confuse not go into here, we should be more familiar with the original a more detailed description.

3, D8 and R8 optimization
D8 optimization
optimization results can be attributed to D8 in general the following four points:

Dex compile times shorter.
dex files smaller.
D8 compiled .dex file has a better runtime performance.
It includes processing Java 8 language support.
You need to take the initiative in gradle.properties new file in Android Studio 3.0:

= to true android.enableD8
Android Studio version D8 3.1 or later will be Dex as the default compiler.

R8 optimization
R8 official document (now open source)

https://r8.googlesource.com/r8

R8 is Proguard compression and optimization alternatives section, and it still uses Proguard keep the same rules. If we only want to use Android Studio in R8, when we open the confusion in build.gradle in time, R8 has been integrated into default in the Android Gradle plugin.
If we are currently using Android Studio 3.4 or Android Gradle plugins 3.4.0 and later, R8 will be used as the default compiler. Otherwise, we must configure the following code in gradle.properties confuse App let's go support R8, as follows:

android.enableR8=true
android.enableR8.libraries=true

So, where R8 advantages compared with the confusion in it?

  • ProGuard and R8 are applied basic name confusion: they all use a short, meaningless names renaming classes, fields and methods. They can also remove the debug attribute.
    However, R8 is more effective inline inline container class, and the class is more aggressive in the delete unused fields and methods. For example, R8 itself is integrated in ProGuard V6.1.1 version, the compression size in the apk, compared with 8.5% ProGuard using R8 apk size is reduced by about 10%. And, with the Kotlin now become the first language of Android, R8 has been particularly optimize some of Kotlin ProGuard not yet available.

  • On the surface, ProGuard and R8 are very similar. They all use the same configuration, so switching between them easily. An enlarged view, then, there are also some differences between them. R8 better inline containers, thus avoiding the object allocation. ProGuard but also has its own advantages, in particular the following points:

1), ProGuard in the enumerated type integer reduced to the original terms will be more powerful. It also passed a constant parameter method, which is usually common for libraries to use application-specific settings called useful.

ProGuard traversing multiple optimization can generally produce a series of optimization. For example, a first pass can pass method parameters constant, so that the next pass can be deleted and further to the parameter value. When you delete a journal code, multiple passes of the effect is particularly evident. ProGuard more effective to remove all trace (including the composition of the log message string operations) aspect.

2), ProGuard applied in pattern matching algorithm to identify and replace short instruction sequences, thereby improving the code efficiency and is more opportunity to optimize the opening. In order to optimize traversal, especially math and string operations can benefit from it.

3, finally, the ProGuard has the unique ability to optimize the use GSON library object serialization or deserialization code to JSON. The library relies heavily on reflection, it is very convenient, but inefficient. ProGuard and optimizations can be more efficient, direct access can be substituted for it.

R8 actual optimization
Next, we will look at the use Awesome-WanAndroid R8, APK volume change, as shown below:

  • It can be seen compared to the APK only after the confusion, the reduced size of 0.1MB, to optimize the effect of Dex part of approximately 5% of the overall APK compression there are about 1.5%.

  • Although reducing the size of APK point of view, 0.1MB little, but the ratio is not small, if you are responsible as a micro letter, Taobao scale App, their volumes are generally nearly 100MB, R8 after use can be reduced the size of 1.5MB.

  • D8 and R8 effect is very powerful, but Jake Wharton Great God Knowledge recent year also D8 and R8, if you want to D8 and R8 are implementation details to learn more about, you can check out his personal blog.

4, remove the debug information and line number information
in explaining what is deubg information and line number information before, we need to understand some knowledge of Dex.

We all know that the load JVM runtime .class file, and Android in order to make the packet size is more compact, more efficient operation when it invented the Dalvik virtual machine and ART both virtual machines are running .dex file, of course ART virtual machines can also run oat file at the same time.

So information Dex documents in the information content and Class files contain is the same, except that Dex file information Class is made to weight, a Dex contains a lot of Class document, and there are relatively large differences in structure , Class is the flow structure, a partition structure of Dex, to index each of the blocks by the offset between the interior of Dex.

In order to apply when problems arise, we are able to display the appropriate debugging information or report the crash or when the initiative to get the call stack can debugItem when debugging to get the corresponding line number, we will add the following rule in confusion configuration :

-keepattributes SourceFile, LineNumberTable
so that it will remain Dex debug and line number information in this case is a configuration diagram of Dex as follows:

Daniel took a year: in-depth exploration of the Android package volume optimization, on a total of 30,000 words recommended collection
can be seen from the figure, Dex file structure is divided into four blocks: header area, the index area, data area, map area . Our debug and line number information is stored in the data area debugItems area.

And debug_items which contains mainly two kinds of information, as follows:

Debugging information: Contains all the parameters and local variables of the function.
The troubleshooting information: contains the mapping between the line number of the instruction set of the source file line numbers.
According to Google's official data, debugItem Dex usually accounts for about 5% of the proportion, if we can remove the debug and line number information, you can slim down further to Dex, but lose the ability to debug information, then, what ways remove debugItem, while allowing crash reporting was only able to get the correct line number it?

We can try to directly modify file Dex, retains a small debugItem, let the system find the line number when the instruction sets the line number and source file line number is consistent, so that any monitor line numbers are reported directly into the instruction set of line numbers.

Each method will have a debugInfoItem, each of which has a debuginfoItem instruction set mapping between the source file and line number line number, which we direct the excess debugInfoItem all deleted, leaving only a debugInfoItem, so that all methods will point to the same debugInfoItem, instruction set and the line number and source file line number in this debugInfoItem consistent, so no matter what way to find the line number to get line numbers are instruction set.

Note that, using this program need to find ways compatible with all virtual machines and thus retain only a debugInfoItem is not enough, we need to debugInfoItem partition, and debugInfoItem table can not be too large.

Debug information on how to remove the Dex ReDex by the StripDebugInfoPass to complete, which is configured as follows:

{
    "redex" : {
        "passes" : [
            "StripDebugInfoPass",
            "RegAllocPass"
        ]
    },
    "StripDebugInfoPass" : {
        "drop_all_dbg_info" : false,
        "drop_local_variables" : true,
        "drop_line_numbers" : false,
        "drop_src_files" : false,
        "use_whitelist" : false,
        "cls_whitelist" : [],
        "method_whitelist" : [],
        "drop_prologue_end" : true,
        "drop_epilogue_begin" : true,
        "drop_all_dbg_info_if_empty" : true
    },
    "RegAllocPass" : {
        "live_range_splitting": false
    }
}

About debuginfo combat will begin immediately below us, before that, let's talk about another optimization point of Dex subcontractors.

5, Dex subcontractors optimization
Dex subcontractors optimization principle
when we APK is too large, the number of ways Dex will be more than 65,536, therefore, we must mutildex subcontracting, but this time Dex might call each other to Dex the method, called this cross-Dex way will cause a lot of redundant information, specifically the following two points:

Extra method id: Cross-Dex dex reservations call causes the current method is called dex id of this redundancy will lead each dex can be stored in the class is reduced, eventually it will lead to an increase in the number of dex compiled, and dex increase data will further aggravate the problem.
Other information redundancy resulting from cross-dex call: in addition to the multi-recording method id is invoked, the need to record more than it belongs to the class definition information and the current method, which can cause string_ids, type_ids, proto_ids redundant information in these parts Yu.
In order to reduce the case of cross-Dex calls, we must try to have the class and method calls are assigned to the same relationship in Dex. But the relationship between the various classes call each other is very complex, it is difficult to achieve optimal conditions.

Fortunately, ReDex of CrossDexDefMinimizer class analysis of the relationship between the calling class and use a greedy algorithm to compute (a certain balance between the effect and dex compiler optimization effect) local optimal solution.

https://github.com/facebook/redex/blob/master/opt/interdex/CrossDexRefMinimizer.cpp

Use "InterDexPass" configuration item can reference each other in the same class as much as possible a Dex, increase class of pre-verify, in order to enhance cold start speed applications.

Dex in the sub-optimization across ReDex dex call redundant information caused by the configuration code is as follows:

{
    "redex" : {
        "passes" : [
            "InterDexPass",
            "RegAllocPass"
        ]
    },
    "InterDexPass" : {
        "minimize_cross_dex_refs": true,
        "minimize_cross_dex_refs_method_ref_weight": 100,
        "minimize_cross_dex_refs_field_ref_weight": 90,
        "minimize_cross_dex_refs_type_ref_weight": 100,
        "minimize_cross_dex_refs_string_ref_weight": 90
    },
    "RegAllocPass" : {
        "live_range_splitting": false
    },
    "string_sort_mode" : "class_order",
    "bytecode_sort_mode" : "class_order"
}

To measure the effect of optimization, we can use this indicator Dex information efficiently, the formula is as follows:

git clone https://github.com/facebook/redex.git
cd redex

If Dex efficiency above 80%, it means basically qualified.

Use ReDex subcontracting optimization, removing debug information and line number information

Here, we use the Redex to further optimize the app-release-proguardwithr8.apk generated in the previous step. (Under macOS environment)

https://fbredex.com/docs/installation

1, first of all, we need to enter the following command over and over again to install Xcode command-line tool
Xcode --install the SELECT-
2, and then, using homebrew installation redex project to use the library dependencies

ANDROID_SDK=/Users/quchao/Library/Android/sdk redex --sign -s wan-android-key.jks -a wanandroid -p wanandroid -c ~/Desktop/interdex_stripdebuginfo.config -P app/proguard-rules.pro -o ~/Desktop/app-release-proguardwithr8-stripdebuginfo-interdex.apk ~/Desktop/app-release-proguardwithr8.apk

Note that right, boost version 2020 February 10 redex need for source code version V1.71 and above, when you use the brew install boost installed boost may get to the boost will be lower than version V1.71, this when the brew may be required to update the version, the use of brew upgrade to a newer version brew warehouse or from the boost official website to download the latest boost to the source directly under / usr / local / Cellar / directory, I currently use a boost V1.7.2 source code download address boost_1_72_0.zip.

https://dl.bintray.com/boostorg/release/1.72.0/source/

It is mentioned from in-depth exploration started when Android optimized Redex classes rearrangement optimization, was stuck in this step, so they could not really complete rearrangement optimization class.

3, then, from the acquired source ReDex Github and switch to the directory REDEX
Git clone https://github.com/facebook/redex.git
CD REDEX
. 4, the next step, and make use autoconf to build ReDex

If you are using gcc, use gcc-5

IVF ./configure && && the make the autoreconf -j4
the sudo the make the install
. 5, and then, the configuration of the config Redex codes
, it is added at run time in accordance Redex redex / config / default.config the configuration file passes different channels optimized to process items of APK of Dex, we can refer to redex / config / default.config this default configuration, which passes the different configuration items have specific optimizations.

App To optimize package size, and we add interdex_stripdebuginfo.config configuration item to delete debugInfo situation and reduce cross-Dex calls, the final interdex_stripdebuginfo.config configuration code is as follows:

{
    "redex" : {
        "passes" : [
            "StripDebugInfoPass",
            "InterDexPass",
            "RegAllocPass"
        ]
    },
    "StripDebugInfoPass" : {
        "drop_all_dbg_info" : false,
        "drop_local_variables" : true,
        "drop_line_numbers" : false,
        "drop_src_files" : false,
        "use_whitelist" : false,
        "cls_whitelist" : [],
        "method_whitelist" : [],
        "drop_prologue_end" : true,
        "drop_epilogue_begin" : true,
        "drop_all_dbg_info_if_empty" : true
    },
    "InterDexPass" : {
        "minimize_cross_dex_refs": true,
        "minimize_cross_dex_refs_method_ref_weight": 100,
        "minimize_cross_dex_refs_field_ref_weight": 90,
        "minimize_cross_dex_refs_type_ref_weight": 100,
        "minimize_cross_dex_refs_string_ref_weight": 90
    },
    "RegAllocPass" : {
        "live_range_splitting": false
    },
    "string_sort_mode" : "class_order",
    "bytecode_sort_mode" : "class_order"
}

6, finally, perform the corresponding command redex optimization
Here we use the command app_release-proguardwithr8.apk Redex on a Dex Dex was subjected to optimization and optimization sub debugInfo removed, it uses a greedy manner such local optimal solution to reduce information redundancy resulting from cross-Dex calls, commands are as follows (Note that you may need to add the path in front of redex Android sdk, because redex used to zipalign tool under sdk):

ANDROID_SDK=/Users/quchao/Library/Android/sdk redex --sign -s wan-android-key.jks -a wanandroid -p wanandroid -c ~/Desktop/interdex_stripdebuginfo.config -P app/proguard-rules.pro -o ~/Desktop/app-release-proguardwithr8-stripdebuginfo-interdex.apk ~/Desktop/app-release-proguardwithr8.apk

Key parameters defined above redex command is as follows:

--sign: apk generated for signing.
-s: signature file to configure the application.
-a: configure the application signed key_alias.
-p: configure the application signed key_password.
-c: needs CONFIG based configuration file to specify redex were Dex treatment.
-o: Specifies the full path generating APK.
Using the above command we can redex APK optimized for re-signing and confusion Wait a moment (if Dex number and size of your APK is large, may be relatively long), it will generate APK optimized: app-release-proguardwithr8-stripdebuginfo- interdex.apk, as shown below:

Daniel took a year: in-depth exploration of the Android package volume optimization, on a total of 30,000 words recommended collection
can be seen, the size of our APK almost no change, because the current APK only a Dex, Dex and the first default does not It will be optimized. To be able to actually see the optimization effect redex, we use a new project to carry out the experiment, the project addresses the following:

redex optimization project addresses Apk

https://github.com/AndroidAdvanceWithGeektime/Chapter22

First, the introduction of a lot of open source libraries, try to change the number of Dex some more. AssembleDebug can then directly compiled by. Further, in order to be more clearly the process, we can enter line export TRACE = 2 so as to be output in the command log redex. Finally, we enter the following command to delete redex dex in the case of cross-dex debugInfo and reduce the call as follows:

redex --sign -s ReDexSample/keystore/debug.keystore -a androiddebugkey -p android -c redex-test/interdex_stripdebuginfo.config -P ReDexSample/proguard-rules.pro  -o redex-test/strip_output.apk ReDexSample/build/outputs/apk/debug/ReDexSample-debug.apk

Finally, we see illustrated in FIG APK volume before and after comparison of the following:

You can see, APK size reduced from 14.2MB to 12.8MB, optimization effect about 10%, the effect is quite obvious. In addition, if you are the greater the number of App Dex, then optimize the effect will be.

6, the tripartite process library

  • The actual development process, we will use a variety of tripartite library. Especially when the project is large, many developers, so the introduction of tripartite library will be very much, for example, was the introduction of a Fresco gallery, then you may not be familiar with this library, you can introduce a Glide, and another person it may well be introduced to his familiar gallery Picasso, so the project may be multiple identical functionality tripartite SDK, this will be the presence of large-scale projects which.

  • Therefore, we do weight-loss when the code needs to be unified tripartite library, for example, the image is loaded libraries, library networks, databases, and other basic library unified, remove redundant libraries.

  • Meanwhile, in the choice of third-party SDK, we can choose one of packet size as an indicator, we should choose those smaller libraries as much as possible to achieve the same functionality.
    For example, for image loading function for, Picasso, Glide, Fresco they can be achieved, but then you Fresco will lead to the introduction of packet size increased a lot, and Picasso increased by only less than 100kb, so the introduction of a different SDK for tripartite package size the impact is not the same.

  • Here, we can use the AS plug Android Methods Count, after installation, it will automatically display the number of ways you tripartite library introduced in build.gradle file.

  • Finally, if we introduce the tripartite library, you can require the introduction of only part of the code, rather than the entire package are the introduction of the code in.

  • Many libraries have code structure design is better, such as Fresco, it will load the pictures of various functions, such as webp, gif functions were stripped, they are in a single library of them. If we only need to Fresco's webp function, then we can be in addition to other libraries webp gave deleted, so you introduce tripartite library is very small, the size of the package come down. As shown by FIG, we retained only the Fresco webp function, the other dependency can be removed.

If you introduce a tripartite structure library not been stripped, we need to modify the source code to extract only the features you need to come out.

7, remove dead code
, we often encounter the following two problems when removing dead code:

Business code only to rise.
Code is too afraid to delete.
Here, there is a good way to accurately determine under which category the online environment will certainly not use the user. AOP way we can do for the Activity, in fact, very simple, we only need to add statistics to the onCreate among each Activity, and then later to the line, if the Activity was counted, it shows it It is still being used.

For those not the Activity class, we can use AOP to cut their constructor, a class if it is used, and that its constructor will certainly be called to. For example, the following is based on the use of certain AspectJ packet constructor code section:

@After("execution(org.jay.launchstarter.Task.new(..)")
public void newObject(JoinPoint point) {
    LogHelper.i(" new " + point.getTarget().getClass().getSimpleName());
}

Wherein, represents a new new constructor is cut, .. parentheses represents the configuration of all parameters match. In addition, we can also do online direct plug-in coverage dead code analysis, to note that, remember to change the server name when registering their reported data.

https://github.com/bytedance/ByteX/blob/master/coverage/README-zh.md

Finally, we can also use the online tool to scan the Simian duplicate code.

https://blog.csdn.net/Love667767/article/details/53558382

8, to avoid Java access method
what access method?
In order to provide internal and external classes like the ability to directly access each other's private members, without violating packaging requirements, Java compiler automatically generates package visibility static access $ xxx methods during compilation, and the need to access other private local members instead call the corresponding access methods.

There are two main ways to avoid access methods:

Note that in the development process in the case where appropriate adjustments possible method of access, such as to remove the private, to the visibility of the package.
Use access method ASM delete generated at compile time.
Because optimization is not very obvious, here is not introduced, the specific implementation details can be found in Java access method of weight-loss delete apk watermelon video, in addition, ReDex also provides a method for access-marking Access this function to remove the code, and, in ReDex also type-erasure feature that effect access-marking and optimization of the same, not only can reduce the package size, but also can improve the startup speed of App.

9, exploit code ByteX Gradle plugin platform optimized plug-ins
if you want to remove access method in the compilation phase of the project, and here I recommend a more direct use of access_inline ByteX plug. In addition to access_inlie, in ByteX there are four very useful code optimization Gradle plugin can help us to effectively reduce the size of Dex file, as follows:

1, during compilation inlining constant field: const_inline.
2, remove unnecessary assignments during compiling the code: field_assign_opt.
3, remove the code during compilation Log: method_call_opt.
4, during the compilation with Get / Set Methods: getter-setter-inline-plugin .
https://github.com/bytedance/ByteX

Weight-loss program resources exploration

  • Known, Android build tools chain AAPT tool used to process the resources, Manifest, Resources, Assets resources via the corresponding ManifesMerger, pool resources ResourcesMerger, AssetsMerger resource combiner for a plurality of different moudule MergedManifest, MergedResources, MergedAssets. They are then processed AAPT young man became R.java, Proguard Configuration, Compiled Resources. The upper left as shown in FIG:

Wherein the effect Proguard Configuration, Compiled Resources as follows:

Proguard Configuration: This is the layout of the various components of the four Views AAPT tool Manifest file declared using the generated configuration confusion, usually stored in the file $ {project.buildDir} / $ {AndroidProject.FD_INTERMEDIATES} / proguard -rules / $ {flavorName} / $ {buildType} /aapt_rules.txt.

Compiled Resources: It is a Zip file format, the file path is generally project.buildDir} {$ / $ {AndroidProject.FD Intermediates} / RES / Resources - $ flavorName} {-} $ {buildType -stripped.ap . After extracting zip, you can see that it contains the res, AndroidManifest.xml and resources.arsc three parts. And, you can be learned from the above APK build process, Compiled Resources will be packaged apkbuilder to APK package, it is actually APK resource bundle.

Therefore, we can modify the file suffix compression different resource file by Compiled Resources to achieve weight-loss effect.

However, note that, resources.arsc file storage is best not compressed, if compression will affect certain properties, especially the impact in terms of cold start time. And, if turned on android on Android 6.0: extractNativeLibs = "false", then, So the file can not be compressed.

The article is not easy, if you liked this article, or to help you hope a lot of attention Oh thumbs forward. Articles will be continuously updated. Absolutely dry! ! !

Guess you like

Origin blog.51cto.com/14775360/2484821