[Android Beauty] Those you don't know apk slimming, make your apk smaller

Source: Internet
Author: User
Tags webp disk usage tinypng

[Android's Beauty] APK slimming, reduce the size of the APK

Keep your apk files as small as possible, and you should remove unused code and resource files. So this section describes how to make the apk smaller, better performance, the download conversion rate is higher, and how to specify the code and resources that are retained or removed during the build apk, before we have analyzed the apk size, there are some improper resource placement, no unified specification, and unreasonable reliance on management, Resource overlap, Dex method Too many problems, resulting in the apk file is larger, the company requires the APK size to be optimized to about 3M. After our efforts finally reached the requirements, but we found that can be smaller.

    • Android beauty apk slimming reduces apk size
    • Analyze the size of the APK
        • Using Android Studio 22
        • Nimbledroid
        • Classshark
    • Slimming the APK
      • Limit compression of resources
        • Use the Webpsvg Picture resource format
        • Using the Andresguard Resource Compression Packaging tool
      • Clear your code and resources
        • Clean up useless code
            • Custom obfuscation Rules
        • Clean up useless resource files
            • Specify the resource file to ignore
            • Enable rigorous detection
        • Clear unused alternative resources
        • To merge Duplicate resources
          • View Resource Recycling
      • Build apk with APK splits
        • Split by Screen density
        • Split by ABI
        • Using multiple versions of APK
      • Dynamic loading of resources
      • Relying on library optimization
      • Plug-in support
      • Using Redex optimization

Analyze the size of the APK

The so-called 工欲善其事, its prerequisite, we have the existing weapon, the following is our common analysis apk size tool.

Using Android Studio 2.2

Android Studio 2.2 New features can directly analyze the size of the APK, double-click to see those that occupy the APK scale, number of methods and so on.

    • Analysis of any APK
    • Check the size of the APK download package, the actual size after decompression
    • decompile resource file, restore resource ID in layout, code
    • Analyze Dex, show the number of methods in each section, and see the size of the library directly

How to use: Build-Analyz APK

With Analyz APK This tool, the following tools can also be basically no

Nimbledroid

Nimbledroid is a system developed by the PhD entrepreneurship team at Columbia University to automate the analysis of Android app performance indicators in both static and dynamic ways, where static analysis can analyze the big file leaderboards in the APK installation package, The size of various well-known SDKs, as well as the proportion of the code as a whole, the size and ranking of various types of files, the number of methods of various well-known SDKs, and the proportion of methods in all Dex, for slow methods, slow third-party SDK and memory leaks.
Measure the speed, network, memory, and disk usage of the build. In short, there are many features that analyze app performance, and if you want to do performance optimizations, you can try using nimbledroid.

View detailed method time-consuming

Specific use of the method, please crossing network:
https://nimbledroid.com/

Note, however, that you should not upload any unpublished products .

Classshark

Classshark is a browsing tool that looks at Android executable files (APK) and currently has two Android apps (APK) and Desktop (jar) versions.
With this tool, you can easily open the Apk/class/jar/res
and other content within the file and analysis.

Specific source code and how to use the details in GitHub:
Https://github.com/google/android-classyshark

By analyzing any of these tools we know that our project is primarily the following files that occupy the APK size:

    • Classes.dex
      Classes.dex is a Java bytecode file generated after the Java source code is compiled,

    • Res
      The main is to store our picture resources

    • RESOURCES.ARSC
      Compiled binary resource file, very many invalid resource files (language)

    • Assets
      The main storage of our cache data files, has been optimized compression, we consider whether the cloud storage.

    • Lib
      Mainly to store our so library, we have optimized the

Now that we know the data that caused our apk to be big, we're going to lose weight.

Slimming APK to limit the compression of resources

To limit the compression of resources, mainly such as Res used in the picture resource files and assets html,db and so on some cache reserved in the APK data file

    • Assets resource compression, using 7zip or Lzma compression mode highest
    • Res image resource compression, using tinypng to optimize the image of Android resources, usually we can ensure that the picture is not distorted, multiple compression several times. Currently Tinypng has support for PNG and JPG images,. 9 Diagram compression
    • Convert non-alpha graphs to JPG form

The above method reduces the size of our picture by 79%.

Use the Webp,svg Picture resource format
    • WEBP is a google developed image Data format, it is a support lossy compression and lossless compression image File format, if the application support to Android 4.0+, then we can use the WEBP format instead of PNG, our resource size can be reduced by more than 50%. or some resources can use SVG image resources smaller.
      Here are their comparison charts:

Here is a handy tool for converting WEBP resources:

    • https://isparta.github.io/
    • Https://imageoptim.com/mac

      • Replace existing images with vectordrawable and SVG images
        Using SVG does not take into account the screen adaptation problem, the volume is very small.
Using the Andresguard Resource Compression Packaging tool

The resource obfuscation tool in the main is to confuse the resource ID length (for example, to turn Res/drawable/icon.png,png into R/s/a.png), while taking advantage of 7z deep compression, the storage of PNG has been changed to occupy less memory, greatly reducing the package volume

Specific source code and how to use the details in GitHub:

Https://github.com/shwenzhang/AndResGuard

Clear your code and resources

Through the above image resource compression can reduce a lot of apk, but this is often not enough, the project also has a lot of unused resource files, duplicate resources, etc., here the main reference Google official documents Https://developer.android.com/studio/build /shrink-code.html#shrink-code part, use Android plugin to turn on Gradle Code shrinking and ProGuard combine use.

    • ProGuardAbility to detect and delete unused classes, fields, methods, and properties from your packaged application, including those containing code libraries, Proguard is a tool that confuses the optimized bytecode, able to remove some unused code, confuse used classes, fields, methods and short names, The APK source code can also be protected with obfuscation

    • Code shrinkingis an android Plugin for Gradle that removes unused resources from your packaged application, including unused resources in the code base. It works in a narrowing with the code so that once unused code has been deleted, any resource no longer references can be safely deleted.

This feature needs to be dependent on:

    • SDK Tools 25.0.10 or higher
    • Android Plugin for Gradle 2.0.0 or higher
Clean up useless code

Code shrinking needs to be used in conjunction with Proguard and added to minifyEnabled true your build.gradle files.

Be aware that code shrinking slows down Gradle compilation and should be avoided using it in your debug build. Android Studio disables Proguard using Instant Run:
For example, the following from build.gradle a file fragment, making code shrinking the release version

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

where getDefaultProguardFile(‘proguard-android.txt‘) the default Proguard settings come from tools/proguard/ folders in the Android SDK

More code reduction can try to use files of the same location proguard-android-optimize.txt (here we have reduced 0.5M) Proguard-rules.pro is your custom Proguard rule.

Each time Build,proguard will output the following files in /build/outputs/mapping/release/ :

    • Dump.txt
      Describes the internal structure of all class files in the. apk file
    • Mapping.txt
      Lists the original classes, method and field names, and the mappings between the code after the confusion. This file is important, and you can use it to translate the obfuscated code when you receive a bug report from the release release.
    • Seeds.txt
      Lists the non-confusing classes and members
    • Usage.txt
      Lists the code that was removed from the. apk
    • Resources.txt
      List the resources that resource is reserved for
Custom obfuscation Rules

In some cases, the default obfuscation profile proguard-android.txt file will remove all the unused code, but it may also mistakenly delete the code you need, so be aware of the following:

    • In the AndroidManifest.xml configured file class
    • Using the Jni interface method
    • The run-time reflection call method (but now Proguard can handle this)

Add-keep to ignore the obfuscated code to the Proguard-rules.pro file, such as:

-keep public class MyClass

You can also use @keep annotations in the code you need to ignore to annotations support library

For more information about customizing the Proguard-rules.pro file, you can refer to Proguard Manual. Here troubleshooting lists some common problems.

Clean up useless resource files

Resource shrinking works only with code shrinking. After you remove all unused code from your code, the application that Resource shrinking can identify which resources are still in use, and you must remove unused code before Resource becomes useless and is erased.

Add shrinkResources true Properties in your Build.gradle file, the corresponding code block is as follows:

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

Resource Shrinker currently does not support removing resource files defined in the values/directory (strings,dimensions,styles,colors) because Android Asset packaging Tool (AAPT) does not allow Gradle plugin to specify pre-defined version resources [issue 70869]

Specify the resource file to ignore

If you want to keep or discard specific resources, create an XML file in your project, use the Resources tab, and specify that each resource is saved in the tool: keep the property and each resource discarded in the tool: Discard property. All two properties accept a comma-delimited list of resource names. You can use asterisks as external cards

The corresponding code block is as follows:

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

You need to save the Res/raw/keep.xml file in the project resources directory, and the file will not be packaged in the apk when build.

Enable rigorous detection

Typically, resource products can accurately determine the use of resources. If you use Resources.getIdentifier() dynamic get the ID of the specified resource, by default, such a resource has a matching name format that is potentially used and cannot be removed.

For example, the following code will cause all img_ prefixes to be stripped of resources.

StringString.format("img_%1d"1"drawable", getPackageName());

resource shrinkerYou can also determine whether to delete a build by searching for the resource name in the code.

<?xml version="1.0" encoding="utf-8"?><resources xmlns:tools="http://schemas.android.com/tools"    tools:shrinkMode="strict" />

Specifying Shrinkmode in the resource file allows you to specify how Gradle will handle the resource file, the default value is safe, and you can designate it as strict (only the resources that are explicitly referenced are preserved, and the processing tools:keep tools:discard of the Annotated resources)

Looking back at the resource Recycling , we'll talk about some problems with XML that can't be erased, and using Shrinkmode to solve this problem.

Clear unused alternative resources

Gradle resource shrinker only removes resources that you do not use in your code, which means that it does not remove alternative resources for different device configurations. If necessary, you can use the Resconfigs property of Android Gradle plugin to remove the alternate resource file.

For example: Our project is suitable for 10 national languages, and the project depends on the V7, V4 and other support package contains 20 national languages, then we can delete the remaining alternative resource files through Resconfigs, which can reduce the size of our apk a lot,

The following code shows how to restrict your language resources, just English and French:

android {    defaultConfig {        ...        "en""fr"    }}

The language specified by the Resconfig property as above. Any resources that are not specified in the language are deleted.

The same picture resources we can do this, for example: We provide a set of xxhdpi image resources, the others are filtered out, so that a large number of support, other third-party library resource files, about this we will say later.

To merge Duplicate resources

By default, Gradle will also have resources with the same name, such as the same name, possibly under a different resource folder, which cannot be removed by the shrinkresources attribute.

A resource merge occurs only when two or more files share the same resource name, type, and qualifier, and the merge priority for the resource is as follows:

Gradle merges resources primarily from the following locations:

    • Src/main/res/Major Resources
    • Gradle using Variant (build type and build flavors)
    • The library relies on the use

Gradle Merge Duplicate resource precedence order is:

Dependencies→main→build Flavor→build Type

For example: If a duplicate resource is specified in your Mian res and a build flavor, Gradle will choose Build flavor

View Resource Recycling

When you Gradle resource shrinker , Gradle Console outputs the log, removing the information from the APK resource. For example:

:android:shrinkDebugResourcesRemoved unused resources: Binary resource data reduced from 2570KB to 1711KB: Removed 33%:android:validateDebugSigning

When the APK is built, the gradle generates a resource.txt in/build/outputs/mapping/release/, which includes details such as resource reference to other resources and details about using or deleting resources.

For example: Find out why @drawable/ic_plus_anim_016 , still included in your apk, search for the file name in Resource.txt, you may find it is referenced by another resource, as follows:

16:25:48.005[QUIET][system.out]@drawable/add_schedule_fab_icon_anim : reachable=true16:25:48.009 [QUIET] [system.out]     @drawable/ic_plus_anim_016

Now you need to know why it @drawable/add_schedule_fab_icon_anim 's still in use, and we know that there should be code references add_schedule_fab_icon_anim .

If you do not use a strict check (which is what is said above shrinkMode ), the same us if we use the string ' #FFFFFF ' in drawable to resource shrinker not remove him in the apk, we can usually see the following information in Gradle console:

10:32:50.590[QUIET][system.out]Markingdrawable:ic_plus_anim_016:2130837506    usedbecauseitformat-stringmatchesstringpoolconstantic_plus_anim_%1$d.

So how do we solve this situation, can be cleaned by the following methods:

    • With Tools:discard, the tools:shrinkmode= "strict" takes effect and specifies that a resource file needs to be deleted. Use when you are sure that the resource file is invalid.
    • Use lint to find unused resources and clean them out

      Open "Analyze" in Android Studio and select "Inspect Code ...", select the entire project, then click "OK"

The size of the APK is a lot smaller here.

Build apk with APK splits

Although we used it well to resource shrinker reclaim some unused resources (V7, V4, Google Service and other libarry resources), some resources were still not cleared.

For example: Those unused multiple sets of alternative resources, or the library within the hidden danger of reference resources and we are not used. Or we will be based on the user's phone to provide different versions of the APK, such as resolution (XXHDPI,MHDPI, etc.), so library. Then we can use APK Splits greatly reduce some useless resources, here we mainly refer to the http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits documentation.

APK SplitsRather than using flavors, it allows the application to build several forms of multiple apk more efficiently.

Multiple APK supports only the following types:

    • Screen density
    • Abi

With the new APK Splits , build hdpi and MDPI versions of the same application, you can share many tasks (such as Javac,dx,proguard). In addition, it will be considered a single variant, and the same test program will be used to test each?? More than one apk.

Split by Screen density
android {  ...  splits {    density {      enable true      "ldpi""tvdpi""xxxhdpi"      ‘small‘‘normal‘‘large‘‘xlarge‘    }  }
    • Enable: Enables screen density split mechanism
    • Exclude: By default, all screen densities are included, and you can remove some density.
    • Include: Indicates which screen density to include
    • Reset (): Resets the screen density list to include only an empty string (this can be implemented, which can be used when working with include to indicate which screen density to use, rather than which screen density to ignore)
    • Compatiblescreens: Represents a list of compatible screens. This will be injected into the matching node in the manifest. This setting is optional.

After the build is complete, you can see multiple versions of the APK in the out/apk/directory.

Split by ABI
android {  ...  splits {    abi {      enable true      reset()      ‘x86‘‘armeabi-v7a‘‘mips‘      universalApk true    }  }}
    • Enable: Enabling the ABI split mechanism
    • Exclude: By default All Abi are included, you can remove some ABI.
    • Include: Indicates which ABI to include
    • Reset (): Resets the ABI list to include only an empty string (this can be implemented, used with include to indicate which ABI to use, rather than which ABI to ignore)
    • UNIVERSALAPK: Indicates whether to package a generic version (including all Abi). The default value is False.

For example: Our project mainly provides XXHDPI image resources, and the project references to many third-party libraries (V7, V4, Google Service and other Libarry resources) we can not use, then we could remove those resources by this method. This way our apk is reduced a lot.

Using multiple versions of APK

Multiple APK Supportis a on Google Play, you can publish different applications for different device configuration features. Each apk is a complete, standalone version of the app, but they share the same app manifest on Google Play and must share the same package name and with the signature. Google Play will automatically match the appropriate apk so that our apk can be built in different versions and requires a resource file to reduce the size of the APK.

With multiple APK launches, we can:

    • Support for different OpenGL APK
    • Support for different screen sizes and densities of apk
    • Support for different device features APK
    • Support for different platform versions of APK
    • Supports different CPU architectures, apk for each apk (e.g. arm, x86,mips, etc.)

      For more information, please refer to https://developer.android.com/google/play/publishing/multiple-apks.html#Concepts

Currently we do a different screen apk based on this program.

Dynamic loading of resources

We can use the dynamic loading form of resources in the project, such as: expression, language, offline library and other resources dynamic loading, reduce the size of the APK.

Relying on library optimization
    • If the minimum version supported by the app is API14, do not use the Android support library, or use the Android supports library separately, which library to introduce (Android-support-ui/android-support-core While support is not very good now, so is Google servie.
    • Use more lightweight libraries instead, or optimize the size of your library, or write better.
    • Delete under the ARMABLE-V7 package so, delete x86 under the package so, basically armable so is compatible with ARMABLE-V7, ARMABLE-V7A Library will have a great improvement in graphics rendering, but the best is based on what we said above to provide multiple versions of the APK, Streamline, or dynamically load so on different platforms.
    • Use H5 to write the interface, the picture cloud gets
    • The resource cache library is not placed under assets and the cloud gets updates.
Plug-in support

In the future for some independent business modules, can be made into plug-in dynamic loading, users need to use, just download a small number of plug-ins.

Using Redex optimization

Redex is a Facebook open source, a tool that reduces the size of the Android app to improve performance, with optimizations like inline and clear zombie code to reduce bytecode, primarily for Dex, which allows the apk to run faster, but requires more testing to crash.

The tutorial is simple and detailed, please refer to the following:
https://code.facebook.com/posts/998080480282805/open-sourcing-redex-making-android-apps-smaller-and-faster/

GitHub Address:
Https://github.com/facebook/redex.git

About the APK slimming we summed up here, there should be a lot of better solutions, if there are mistakes, welcome to add.

For more Android beauty, read the "Android beauty from 0 to the best of the Road" series article

The level is limited, if have errors and omissions, welcome to correct, criticize, if need reprint, please indicate source –http://blog.csdn.net/vfush, thank you!

Fuchenxuan
Source: Http://blog.csdn.net/vfush
Welcome to my personal site: http://fuchenxuan.cn
Reprint please specify the source –http://blog.csdn.net/vfush

[Android Beauty] Those you don't know apk slimming, make your apk smaller

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.