We all know that the performance of the application is very important in the development, but it is also the difficulty of optimization and improvement. This chapter focuses on the performance practice of Android, which starts from reducing the size of APK to improve the user experience.
The original address developer.android.com/topic/perfo…
This article is edited and output jointly by Aixueyuan platform
Original author: Love School – Mobius Ring
Users often avoid downloading apps that look too big, especially within the app market where devices are connected to 2G and 3G networks or paid networks. This article describes how to reduce the size of your application APK so that more users can download your application.
Understand APK file structure
Before discussing how to reduce the size of your application, it is helpful to understand the file structure of an application’s APK. An APK file contains a ZIP archive that mainly contains all the files for your application. These files include Java class files, resource files, and file resources containing compilations.
An APK contains the following directories:
META_INF/
: containsCERT.SF
andCERT.RSK
Signature file, as wellMANIFEST.MF
Manifest files.assets/
: Contains the assets of the application. The application can use oneAssetManager
Object retrieval.res/
: contains cannot be compiledresources.arsc
File resources.lib/
: contains compiled code and is a processor-specific software layer. This directory contains subdirectories assigned for each platform type, such asarmeabi
.armeabi-v7a
.arm64-v8a
.x86
.x86_64
, andmips
.
APK also contains the following files. Of these, only Androidmanifest.xml is mandatory.
resources.arsc
: Contains compiled resources. This file contains the from folderres/values/
XML content for all configurations under. The wrapping tool extracts this XML content, compiles it into binary form, and archives the content. This content includes language strings and styles as well as paths that do not exist inresources.arsc
The contents of the file, such as layout files and images.classes.dex
: contains the format in which the compiled classes in the DEX file can be understood by the Dalvik/ART virtual machine.AndroidManifest.xml
: contains the Android core manifest file. This file lists the application name, version, access rights, and referenced library file for the application. The file uses Android binary XML format.
Reduce the number and size of resources
The size of APK affects how fast an application loads, how much memory it uses, and how much power it consumes. One simple way to make your APK smaller is to reduce the number and size of resources it contains. In particular, you can remove resources that your application is no longer using, and you can use Drawable image files. These and several other approaches discussed in this section reduce the overall size of your APK by reducing the resources used by your application.
Remove unused resources
Android Studio includes a static code parser tool lint that can be used to retrieve the resource folder RES/to find resources that your code does not reference. When the Lint tool finds a potential unused resource in your project, it prints a message like the following example.
res/layout/preferences.xml: Warning: The resource R.layout.preferences appears
to be unused [UnusedResources]
Copy the code
⚠ ️ :lint
Tool cannot scanassets/
Directories, reference assets by reflection, or you connect library files to your application. At the same time, it does not delete resources; Just remind you of their presence
The library files your code depends on May contain resources that are not being used. If you enable shrinkResources in your build.gradle build file, it means that Gradle automatically removes these resources.
android {
// Other settings
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}}}Copy the code
To use shrinkResources, you must enable code compression. During the build process, ProGuard first removes unused code but leaves unused resources idle. Gradle then removes the unused resources.
For more information about ProGuard and other ways that Android Studio provides to help you reduce the size of Your APK, see Shrink Your Code and Resources.
On Android Gradle plug-in 0.7 and later, you can declare configurations supported by your application. Gradle builds the system by using the resConfig and resConfigs categories and the default configuration defaultConfig option. The build system can then reduce the size of APK files by preventing unsupported configuration resources from appearing in APK files. For more information about this feature, see Remove Unused Alternative Resources
Minimize the use of resources from external libraries
When we develop an Android application, you often use external libraries to improve the application’s usability and versatility. For example, you can reference the Android Support Library to improve the user experience of your application on older devices, or you can use Google Play Services within your application to retrieve text for automatic translation.
If a library is designed for use on a server or desktop. It may include many objects and methods that your application does not need. To include only what you need, you can edit the library’s files if the library’s certificate allows you to. You can also use an alternative method to move a specified function module to your application.
⚠️ : ProGuard can remove unnecessary code import libraries, but it cannot remove large internal dependencies of a library.
Only specific densities are supported
Android supports a very large set of devices, including a wide variety of screen densities. In Android 4.4 (API level 19) and later, the framework supports various densities: LDPI, MDPI, TVDPI, HDPI, XHDPI, XXHDPI, XXXHDPI. Even though Android supports all of these densities, you don’t need to export resources for each density.
If you know that only a small percentage of users’ devices have specific densities, it is worth considering whether those densities need to be included in your application. For a particular screen density, if you don’t include that resource,Android will look for existing resources that are similar to other screen densities.
If your application only needs scaled down images, you can save even more space by placing unique images under the drawable-nodpi/ file. We recommend that every application include at least one xxHDPI image variant.
For more information about Screen density, see Screen Sizes and Densities
Use drawable objects
Some images do not require a static image resource; The framework can draw images dynamically at run time. Drawable objects (
in XML) can take up a small amount of space inside your APK. In addition, the monochrome image produced by the XMLDrawable object conforms to the guidelines of Material Design.
Reduce resource
For changes to an image, you can include a separate resource, such as coloring, shading, or rotating versions of the same image. However, we recommend that you reuse the same set of resources and customize them as needed at run time.
Android provides some tools to change the color of resources, and Android :tint and tintMode properties are available on Android5.0 (API21) and later. For lower platform versions, the ColorFilter class can be used.
If one resource can be rotated to produce another, you can import only one. The following code snippet provides an example of turning a “thumb up” 180 degrees on its axis to “Thumb down” :
<? 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" />
Copy the code
Images are rendered by code
You can also reduce your APK size by programmatically rendering your images. Procedural rendering makes room because you don’t need to store images to your APK files.
At PNG file
During the build process, the AAPT tool can use lossless compression to optimize the image resources placed in the RES /drawable/ directory, thereby reducing the image footprint. For example, the aapt tool can convert a true-color PNG that does not require more than 256 colors to an 8-bit PNG with a color He palette. In this way, images of the same quality take up less memory.
Please note that AAPT has the following restrictions:
aapt
Cannot be compressedasset/
PNG file in the directory.aapt
Tools to optimize image files require 256 or fewer colors.aapt
The tool may optimize compressed PNG files multiple times. To avoid this you can use it in Gradle filescruncherEnabled
Flag disables processing of PNG files.
aaptOptions {
cruncherEnabled = false
}
Copy the code
Compress PNG and JPEG files
You can use tools like PngCrush, PngQuant, or Zopflipng to reduce PNG file sizes without losing image quality. All of these tools can reduce the size of PNG files while preserving perceived image quality.
The PngCrush tool is particularly effective: this tool iterates through PNG filters and zlib(Deflate) parameters, compressing images using a combination of filters and parameters. It then puts the configuration that yields the best compressed output.
To compress JPEG files, you can use tools such as packJPG and Guetzli.
Use WebP format files
For Android 3.2 (API level 13) and later, you can also use WebP image format files instead of PNG and JPEG files. The WebP format provides lossy compression (such as JPEG) and transparency (such as PNG), which provides better compression than JPEG or PNG.
With Android Studio, you can convert existing BMP, JPG, PNG, or static GIF images to WebP format. For more information, see Create WebP Images Using Android Studio.
⚠️ : Google Marketplace accepts APK launch ICONS in PNG format only.
Using vector diagrams
You can use vector graphics to create resolution-independent ICONS and other scalable media. Using these graphics can greatly reduce your APK size. In Android, vector graphs are represented as VectorDrawable objects. VectorDrawable object, a 100-byte file that can be used to render screen-sized images.
However, the system takes a lot of time to render each VectorDrawable object, and the larger the image, the longer it takes to render it on the screen. Therefore, consider using these vector graphics only when displaying small images.
For more information on how VectorDrawable objects work, see Working with Drawables.
Animate images using vector graphics
You cannot use AnimationDrawable objects to create frame animations because doing so requires a separate bitmap file for each frame of animation, which greatly increases the size of the APK.
You should use AnimatedVectorDrawableCompat to create vector animations.
Reduce native and Java code
There are several ways you can reduce the size of Java and Native code bases in your application.
Remove unnecessary code generation
Make sure to understand the footprint of any code which is automatically generated by the tool. For example, many protocol buffering tools generate too many methods and classes that can double or triple the size of your application.
Avoid enumerations
An enumeration can increase the size of your application’s classes.dex file by about 1.0 to 1.4 KB. For complex systems or shared libraries, these additions can quickly augment the file. If possible, consider using the @Intdef annotation and ProGuard to strip enumerations out and convert them to integers. This type of conversion is safe and reliable for holding all enumerated types.
Reduce the size of the local binary
If your application uses native code and the Android NDK, you can also reduce the size of the release version of your application to optimize your code. Two useful techniques are to remove debug symbols rather than extract local libraries.
Remove debug symbol
The point of using debug symbols is that your application still needs to be debugged during development. Use the ARM-eabi-strip tool (provided with the Android NDK) to remove unnecessary debug symbols from the local library. After that, you can compile and publish the build.
Avoid extracting local libraries
When building applications release, if you are in your application’s manifest file, the set properties of the element tag is as follows: android: extractNativeLibs = “false”, the APK package will not be compressed. So file. Disabling this flag prevents the PackageManager from copying.so files from your APK to the file system during application installation, which has the benefit of allowing you to update your application in smaller sizes.
Maintain multiple lean APKS
APK may contain content that users download but never use, such as regional or language information. To create a minimal download for the user, you can split your application into several APKs, differentiating factors such as screen size or GPU hardware support.
When users download your application, their device receives the correct APK based on device functionality and Settings. This way, the device does not receive functionality that the asset device does not. For example, if a user has an HDPI device, they do not need the xxXHDPI resources included relative to the higher density device.
For further information, please refer to Configure APK And Maintaining Multiple APKs.