[Android performance optimization interview questions] How to slim down apk

How to slim down apk

What do you want to examine with this question?

  1. Do you understand the real-life scenarios of how to slim down apk? Are you familiar with the scenarios caused by how to slim down apk?

Knowledge points to investigate

  1. How to slim down apk and use it in projects and basic knowledge

How should candidates answer

The size of the APK has a great impact on the app loading speed, memory size and power consumption. Generally speaking, users do not like to download apps with too large APK size. Especially for users with limited traffic and mobile phone memory, APKs that are too large will often put them off, so they need to slim down their APKs.

If you want to slim down your APK, you must first understand the structure of the APK. Only by understanding what parts the APK is composed of can you slim down the APK in a targeted manner.
APK mainly consists of the following parts:

  • META-INF/: Inclusion name text itemCERT.SF, CERT.RSA, manifest text item MANIFEST.MF.
  • assets/: Stores resource files. These resources will not be compiled into binaries.
  • lib/: Contains some referenced third-party libraries.
  • resources.arsc: Contains all resources in res/values/, such asstrings,styles, and others Resource path information not included inresources.arsc, such as layout files, pictures, etc.
  • res/: Contains resources in res that are not stored in resources.arsc.
  • classes.dex: Java source code file that can be understood by the android virtual machine after dx compilation.
  • AndroidManifest.xml: No need to explain this

Use android studio --> build --> Analyze APK to check the file size of each of the above parts:

As shown in the figure below: the space occupied is mainly code, res and lib. Because there are no files in my assets, it does not seem to occupy much space. In fact, if there are many files in assets, it will still occupy a lot of space. big space. Therefore, when slimming down the APK, mainly focus on 代码, res, lib and assets. Key aspects to consider:

img

Reduce the number and size of resource files

It must be understood that a very simple way to slim down your APK is to reduce the number and size of resource files.

Remove useless resources

Uselint tool to detectres/ whether there are unused resources

However, for some third-party libraries, it may not be detected using lint. We can useshrinkResources to delete useless resources in the library file and use it with proguard to compress the code

android {
    
    
    // Other settings

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

Remove unused spare resources. For example, for some third-party libraries, they may support dozens of languages ​​due to internationalization issues, but our application may only need to support Chinese. In this case, we can use resConfig or resConfigs to solve.
The following code shows how to limit the language resource to support Chinese only:

android {
    
    
    defaultConfig {
    
    
        ...
        resConfigs "zh"
    }
}
Use libraries that minimize resources

When developing projects, many third-party libraries are often used, but the third-party libraries may often be very large, so how to compress them?

  • Use ProGuard to compress the code, and then use it with shrinkResources. For the method, see the use of shrinkResources above.

  • However, ProGuard can only compress some unused code in the library itself, but the library itself may still rely on other third-party libraries, and ProGuard cannot effectively remove these libraries.
    Many third-party libraries provide multiple versions, such as full versions, streamlined versions, and special versions for a certain function. You only need to choose the smallest version library that can contain the functions you need. Of course, it would be better if you can get the source code and extract the functions you need yourself.

Only supports certain screen densities

Android supports a variety of screen density devices. Android 4.4 and above supports: ldpi, mdpi, tvdpi, hdpi, xhdpi, xxhdpi and xxxhdpi. Although Android supports so many screen densities, you don’t need to support them all and you can choose support based on your needs.

Using drawable objects

For some simple images, you can use Drawable XML instead of using pictures.

Reuse resources

The same picture can be reused for some similar images.

  • Images with the same shape but different colors and shadows; in Android 5.0 (API level 21) and above, you can use android:tint, tintMode Wait for the properties to be adjusted. You can use ColorFilter to adjust below Android 5.0.

  • Image with the same shape and color but different angles; you can use rotate etc. to adjust the angle to achieve reuse effect. For example:

    <?xml version="1.0" encoding="utf-8"?>
    <rotate xmlns:android="http://schemas.android.com/apk/res/android"
        android:drawable="@drawable/ic_thumb_up"
        android:pivotX="50%"
        android:pivotY="50%"
        android:fromDegrees="180" />
    
code rendering

You can also render through code instead of using images, such as using a custom View to draw. The number of pictures has been reduced, and the APK has naturally become slimmer.

Compress PNG files

The AAPT tool will automatically perform lossless compression on the PNG image resources in the res/drawable/ folder during the build process. For example, a true-color PNG image may be converted into an 8-bit palette image (PNG8) if it actually requires no more than 256 colors. The converted image quality is not reduced and only takes up less memory.

Compress PNG and JPG

You can usepngcrush, pngquant or come压缩JPG图片. guetzli or packJPG useKai PNG fragment. zopflipng

Using WebP

You can use WebP instead of JPG and PNG images. WebP While retaining the advantages of JPG and PNG, it can provide better compression and achieve a smaller size.

注意事项:启动图标最好不要用WebP,因为谷歌商店只接受启动图片格式为PNG的APK。
Use vector graphics

You can use vector graphics to draw resolution-independent icons and other scalable media files. A clear image as large as the entire screen may only require 100-byte size if using vector images.
However, using vector graphics will take more time for the system to draw, so it is best to only use vector graphics on smaller images.

Use vector graphics for animated images

Do not useAnimationDrawable to create frame animations, otherwise using one image per frame will take up a lot of space. At this time you should use AnimatedVectorDrawableCompat.

Remove unnecessary generated code

Make sure you understand the purpose of automatically generated code. For example, there are many protocol buffer tools that automatically generate a lot of code that you may not use.

Avoid using enumerations

A single enumeration can increase the apk size by 1.0 to 1.4 KB. For complex systems or shared libraries, this may add up to a considerable APK size.
If possible, consider using the @IntDef annotation and ProGuard to strip the enums and convert them to integers. This type conversion preserves the type safety advantages of enumerations.

Reduce the size of local binaries

If your APP uses native code and Android NDK, you can optimize the code through two methods to reduce the APK size.

  • Remove Debug symbols
    Use the arm-eabi-strip tool provided in the Android NDK to remove unnecessary Debug symbols in the Native library.

  • Avoid extracting local libraries
    Before Android 6.0, so files will be compressed into apk. When the system installs the application, it will decompress the so files to the data partition, so that the same There will be two copies of the so file, one in the apk and one in the data area, which takes up twice as much space. Starting with Android 6.0, you can use a new attribute in AndroidManifest.xml:

    As follows: This attribute tells the system not to decompress the so file from the apk, and modify the System.loadLibrary call to open the so file directly from the apk:

    <application
     android:extractNativeLibs=”false”
     ...
    >
    
Maintain multiple lite versions of APKs

Your app may contain a lot of content that users won't use at all, such as regional and language information. You can provide different versions of your APK based on factors such as screen size or GPU texture support. When a user downloads an APK, a specific version of the APK will be downloaded based on the characteristics and settings of the phone, so that the user will not download content he does not need at all.

android {
    
    
  ...
  splits {
    
    
    //根据屏幕像素密度来创建多个APK
    density {
    
    
      enable true
      //根据屏幕密度创建两个版本APK,"mdpi", "hdpi"
      reset()
      include "mdpi", "hdpi"
    }
    //根据手机cpu指令集分类创建多个APK
    abi {
    
    
      enable true
      //创建 "x86", "x86_64"两个版本APK
      reset()
      include "x86", "x86_64"
    }
  }
}

Let’s compile the APK and see the results:

img

Analyzing the above picture, you can see that 6 APKs were generated. Why 6?
Answer:

First of all, there are three versions of screen density (mdpi, x86_64, gralde will also generate a default version containing all screen density resources), ABI instruction set There are two versions (the default compilation of gralde will not add APKs containing all ABI instruction set versions. If you want to add it, you need to add universalApk true in the abi code block), and they are combined into 6 kind. Each APK will only contain its corresponding resources. For example, app-hdpiX86-debug.apk will only contain resources with a screen density of hdpi and X86 library file.
If your mobile phone’s CPU instruction set is x86 and the screen density is hdpi, then you will download app-hdpiX86-debug.apk


at last

I have compiled a collection of Android interview questions. In addition to the above interview questions, it also includes [Java basics, collections, multi-threading, virtual machines, reflection, generics, and concurrent programming , Android's four major components, asynchronous tasks and message mechanisms, UI drawing, performance tuning, SDN, third-party frameworks, design patterns, Kotlin, computer network, system startup process, Dart, Flutter, algorithms and data structures, NDK, H. 264, H.265. Audio codec, FFmpeg, OpenMax, OpenCV, OpenGL ES
Insert image description here

Friends in need can scan the QR code below to receive all interview questions + answer analysis for free! ! !

Guess you like

Origin blog.csdn.net/datian1234/article/details/134837248