How to slim down your Android Installation File (APK)

Source: Internet
Author: User

How to slim down your Android Installation File (APK)

 

It is an indisputable fact that the apk file of Android is getting bigger and bigger. In Android or the original version, the apk file size of an app is only about 2 MB. Now, the size of the apk file of an app has been upgraded to 10 MB to 20 MB. The explosive growth in the size of apk files is mainly because users' expectations for app quality are getting higher and higher, as well as developers' development experience is increasing. These are embodied in the following aspects:

  • Dpi diversity of Android devices ([l | m | TV | h | x | xx | xxx] dpi)
  • Evolution of the Android platform, improvement of development tools, and rich open-source class library ecosystems
  • Users' expectations for high-quality UI
  • Other reasons

    Android Developers should consider the final release of a lightweight app as a best practice when designing an app. Why? First, this means that you have a concise and easy-to-maintain code base. Second, the official App Store sets the extended package File Download option for apk files larger than 50 MB. It is easier for users to download apk files smaller than 50 MB. Finally, our application environment is an environment with limited bandwidth and limited storage space. The smaller the apk installation file, the faster the download, and the faster the installation, a virtuous circle, in the end, the user may be praised for this.

    In most cases, the apk size increases to meet the needs and expectations of consumers. However, I think the growth of apk size has exceeded the user's expectation for app growth. So, to a large extent, the programs in the official app store can be reduced to half or more of their current size. In this article, I will write some tips on how to slim down the apk file. I hope you will like it.

     

    APK File Format

    Before we talk about how to slim down the apk, let's take a look at the structure inside the apk file. To put it simply, an apk file is a compressed package containing some files. As a developer, we useunzipCommand to decompress the apk file and check the internal structure of the apk. The following file structure is usedunzip .apk 1 The command obtained:

     

    /assets/lib  /armeabi  /armeabi-v7a  /x86  /mips/META-INF  MANIFEST.MF  CERT.RSA  CERT.SF/resAndroidManifest.xmlclasses.dexresources.arsc

    We may be familiar with most of the above files and directories. They are the same as the project structure we saw when developing an app, including:/assets,/lib,/res,AndroidManifest.xml. There are some files that we may see for the first time. Generally,classes.dexIt contains the compiled class file of the Java code we wrote;resources.arscContains pre-compiled resource files (such as values files and XML drawables files .).

     

    Because the apk file is a simple compressed file, it has two sizes: The size before compression and the size after compression. This article focuses on the size after compression.

    How to Reduce the apk File Size

    You can reduce the size of the apk file from several aspects. Because each app is different, there is no absolute rule to slim down the apk file. As an important part of the apk file, we can start with them:

    • Java source code
    • Resource files (resources/assets)
    • Native code

      Therefore, the next step is to reduce the size of these components and the size of the entire app.

      Good coding habits

      This is the first step to reduce the size of the apk file. You need to put your code in the palm of your hand. You need to remove the dependency libraries from all useless parts, so that your code is better than a day and your code is continuously optimized. All in all, keeping the latest code simple is a crucial part of reducing apk files.

      Of course, it is easy to start a project from scratch and maintain a concise code Foundation for the project. The older the project, the more difficult the job is. In fact, a project with a large historical background must process various dead code and useless code. Fortunately, there are many development tools that can help us do these things ......

      Use Proguard

      Proguard is a powerful tool that can help you confuse, optimize, and compress code During code compilation. It has a function called tree-shaking to reduce the size of apk files. Proguard traverses all your code and finds useless code. All these unattainable (or unnecessary) code will be cleared before the final apk file is generated. Proguard will also rename your class attributes, classes and interfaces, while the entire Code remains lightweight as much as possible.

      Maybe now you will think Proguard is a very effective tool. But the larger the capability, the greater the responsibility. Many developers now think that Proguard is a little effort-free because it relies heavily on reflection. The developer must configure Proguard for any classes or attributes that need to be processed or cannot be processed.

      Widely used Lint

      Proguard only works for Java code. What resource files does it work? For example, an imagemy_imageInres/drawableFolder, not used, Proguard will only removeRClass, but the image is still in the folder.

      Lint is a static Code Analyzer, you only need to call./gradlew lintThis simple command can help you check all useless resource files. After detection, it provides a detailed list of resource files and lists useless resources under the "UnusedResources: Unused resources" area. You can safely remove unnecessary resources without reflection.

      Lint will analyze resource files (such/resFiles under the folder), but the assets file (/assetsFolder ). In fact, assets files can be accessed directly through their file names, instead of being referenced in Java or XML. Therefore, Lint cannot determine whether an asset file is useful in the project. It all depends on the developer's maintenance of this folder. If you do not use an asset file, you can clear it directly.

      Select resource files

      Android supports multiple devices. The Android system design allows it to support the diversity of devices: screen density, screen shape, screen size, and so on. Android 4.4 supports ldpi, mdpi, tvdpi, hdpi, xhdpi, xxhdpi, and xxxhdpi. But what you need to know is that Android supports so many screen density does not mean that you need to provide corresponding resource files for each screen density.

      If you know that only a few users are using some screen density devices, you do not need to use resource files with the corresponding screen density. Personally, I only provide hdpi, xhdpi, and xxhdpi2 screen density support for my applications. If some devices do not have these screen density, do not worry. The Android system will automatically use the existing resources for device computing and then provide resource files.

      The reason for doing so is simple. First, the screen density of these devices will cover 80% of my users. Secondly, the screen density of xxxhdpi is only preparing for future devices, but it is not yet available. Finally, I really don't care much about low screen density (such as mdpi and ldpi). No matter how hard I work for these screen density, the results are sad, it is better to directly scale the hdpi resource file in the Android system to match the corresponding low-end models.

      Similarlydrawable-nodpiSaving space by keeping a file in the folder. Of course, the premise is that you think that you can accept the effect after the file is scaled accordingly or there is very little chance that the file will appear.

      Minimum resource file configuration

      Android development often relies on a variety of external open-source code libraries, such as the Android Support Library, Google Play Services, and Facebook SDK. However, not all resource files are used in these libraries. For example, Google Play Services may provide translation for other languages, and your app does not need translation for this language, the Library also contains the mdpi resource files not supported by my app.

      Fortunately, you can configure the build system of your app from Android Gradle Plugin 0.7. This is mainly through the configurationresConfigAndresConfigsAnd the default configuration options. The following DSL prevents aapt (Android Asset Packaging Tool) from Packaging unnecessary resource files in the app.

       

      defaultConfig{    // ...    resConfigsen,de,fr,it    resConfigsnodpi,hdpi,xhdpi,xxhdpi,xxxhdpi}


       


       

      Compressed image

      Aapt (Android Asset Packaging Tool) has built-in fidelity image compression algorithms. For example, a 256-color PNG image is converted into an 8-bit PNG file by aapt through a color palette. This helps you reduce the size of the image file. Of course, you can also search for the corresponding optimization tools through Google, such as pngquant, ImageAlpha, and ImageOptim. You can select a suitable tool.

      You can also optimize an image file that only exists on the Android platform, which is 9-patches. As far as I know, I have not found any optimization tool for this file. However, you only need to ask your designer to minimize its scalable areas and content areas. This not only reduces the size of resource files, but also makes it easier to maintain resource files in the future.

      Limit the number of cpu architectures supported by the app

      Generally, Android uses Java code to meet most of the requirements, but there are still a few cases that require some native code. As with the previous opinionated resource files, you can use these native code opinionated. In the current Android ecosystem, it is enough to allow your app to support the armabi and x86 architectures. Here is a pretty good article about how to slim down the native code library. For more information, see.

      Reuse as much as possible

      Reusing resources may be one of the most important optimization skills you need to know when developing mobile apps. For exampleListViewOrRecyclerView, Reuse can help you keep the interface smooth during list scrolling. Reuse can also reduce the size of the apk file. For example, Android provides several tools to re-color an asset file. In Android L, you can useandroid:tintAndandroid:tintModeIn earlier versions, you can useColorFilter.

      If there are two types of images in the system, one is obtained by turning another image 180 °, then you can remove one type of image and implement it through code. For example, you have two types of images named respectivelyic_arrow_expandAndic_arrow_collapse:

       

      You can remove it directly.ic_arrow_collapseFile, and thenic_arrow_expand CreateRotateDrawable. This method can also reduce the workload of designers:

       

           
           

       

       

      Use code to render images when appropriate

      In some cases, rendering images directly using Java code can also achieve good results. For example, frame-by-frame animation is a good example. Recently, I have tried some Android Wear development and learned about the Android wearable support library. Like other Android support libraries, there are some tools in this library to process wearable devices.

      However, I was surprised that when I constructed a "Hello World" example, the final apk file was 1.5 MB. So I quickly studiedwearable-support.aar File. We found that this library has two frames-by-frame animations and supports three different screen density types: A "success" animation (31 frames) and an open on phone animation (54 frames ).

       

      This frame-by-frame success animation is calledAnimationDrawableDefined:

       

               
               
                
                 
                  
                   
                 
                  
                   
                    
                     
                      
                       
                        
                         
                          
                           
                            
                             
                              
                               
                                
                                
                               
                              
                             
                            
                           
                          
                         
                        
                       
                      
                     
                    
                   
                  
                 
                
               
              
             
            
           


       

       

      In this way, (I am ironic) 33 ms is displayed for each frame, which keeps the animation at a frequency of 30 FPS. If each frame is 16 ms, the entire database will be twice as large as before. If you look at the source code, you will find it interesting. Ingeneric_confirmation_00175This frame (15 rows) will continue to display for 333 ms.generic_confirmation_00185Follow it. This optimization saves 9 similar frames (from 176 frames to 184 frames ). But what's amazing at the end is thatwearable-support.aarUnexpectedly, the nine completely useless frames are included and displayed at the screen density of three. 3

      Rendering such an animation in code is obviously time-consuming. However, when you maintain the animation running at a frequency of 60 FPS, You can greatly reduce the size of the apk. At the time of writing this blog post, Android has not provided a tool to render such an animation. However, I hope Google is developing a new generation of lightweight real-time rendering systems to ensure detailed presentation of material design. Of course, design tools such as Adobe After Effect to VectorDrawable can also provide a lot of convenience.

      How can we proceed further?

      All the above moves are concentrated on app or library developers. Maybe we can make some changes to the apk size in the app distribution channel? I want to make some improvements on the app distribution server or in the official app store. For example, the official app store can expect users to bind the corresponding native Library to the device when installing the app and discard those useless ones.

      Similarly, we can imagine packaging an application only based on the configuration of the target device. Unfortunately, this may damage an important feature of the Android ecosystem: Configuring hot replacement. In fact, Android was initially designed to handle various real-time configuration changes (language, screen redirection. If we remove the resource files that are not compatible with the target screen, this can greatly reduce the file size. However, Android needs to handle real-time screen density changes. Even if we assume that this feature is abolished, we still need to process images and other configurations (such as screen orientation and minimum width) designed for different screen density ).

      The apk package on the server looks powerful. However, this would take a big risk, because the apk that is finally sent to the user will be completely different from the server that the developer sends. Distributing apk files with missing resources may cause app crash.

      Summary

      The design is to find the best solution in a collection. Obviously, the size of the apk file is a constraint. Don't be afraid to relax one constraint to make multiple aspects better. For example, if you want to reduce the rendering effect of the UI, do not hesitate because it can reduce the size of the apk and make the app run more smoothly. 99% of your users do not feel that the UI quality is lower, but they will notice that the apk file is smaller and the running is smoother. In short, you need to consider all aspects of the app, rather than just a few aspects.

       

      Putting Your APKs on Diet

      Original Author: Cyril Mottier

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.