Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the methods of APK structure optimization

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what are the methods of APK structure optimization". In the daily operation, I believe that many people have doubts about the methods of APK structure optimization. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "what are the methods of APK structure optimization?" Next, please follow the editor to study!

01 things about the structure of APK

Only when you know yourself and the enemy can you fight a hundred battles. It is helpful for us to understand the structure of the application APK. The APK file consists of an ZIP archive that contains all the files that make up the application. These files include Java class files, resource files, and files that contain compiled resources.

APK contains the following directories:

META-INF/: contains CERT.SF and CERT.RSA signature files as well as MANIFEST.MF manifest files.

Assets/: contains application resources that an application can retrieve using an AssetManager object.

Res/: contains a resource resources.arsc that has not been compiled into.

Lib/: contains compiled code specific to the processor software layer. This directory contains subdirectories for each platform, such as armeabi,armeabi-v7a, arm64-v8a,x86,x86_64, and mips.

Resources.arsc: contains compiled resources. This file contains the XML content in all configurations of the res/values/ folder. The packaging tool extracts this XML content, compiles it into binary format, and archives the content. This content includes language strings and styles, as well as content paths, such as layout files and images, that are included directly in the resources.arsc file.

Classes.dex: contains classes compiled in a DEX file format that the Dalvik / ART virtual machine can understand.

AndroidManifest.xml: contains the core Android manifest file. This file lists the name, version, access rights, and referenced library files of the application. The file uses Android's binary XML format.

Generally speaking, the larger parts of the APK structure are generally classes.dex, lib, res, assets files or directories. So next we will explain these four situations.

02 reduce classes.dex

Classes.dex contains all the Java code. When you compile your application, gradle converts .class files in all your modules into .dex files and synthesizes them into a classes.dex file.

A single classes.dex file can hold approximately 64K methods. If you reach this limit, you must enable multidexing in your project. This will create another classes1.dex file to store the rest of the methods. So the number of classes.dex files depends on your number of methods.

Reduce the use of the third library

With the frequent change of business and the increase of complexity, we tend to use third-party Libaray. Sometimes we may only use a small part of the function, so we need to carefully consider full reference. From my development experience, I would rather refer to my own implementation than introduce a third-party library.

Avoid enumeration

An enumeration can add a size of approximately 1. 0 to 1. 4 KB for your application's classes.dex file. These additions can be quickly accumulated into complex systems or shared libraries. If possible, consider using the @ IntDef annotation, which retains all the type safety advantages of enumerations.

Use ProGuard

The following code from the build.gradle file is used to enable code compression for the release build:

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

In addition to the minifyEnabled attribute, there is also a proguardFiles attribute that defines the ProGuard rule:

The getDefaultProguardFile ('proguard-android.txt') method gets the default ProGuard settings from the Android SDK tools/proguard/ folder.

Tip: for further code compression, try using a proguard-android-optimize.txt file located in the same location. It includes the same ProGuard rules, but also other optimizations that perform analysis at the bytecode level (within and between methods) to further reduce the APK size and help improve its speed.

The proguard-rules.pro file is used to add custom ProGuard rules. By default, the file is located in the module root (next to the build.gradle file).

03 optimize resource files in assets and res

Extraneous remarks

What res/raw and assets have in common:

The files in both directories will be packaged and stored intact in the apk package and will not be compiled into binary.

The differences between res/raw and assets:

The files in res/raw will be mapped to R.java files, and the files under the resource ID that is R.raw.filenamebot assets folder will not be mapped to R.java when accessing, and the AssetManager class will be needed when accessing.

Res/raw cannot have a directory structure, while assets can have a directory structure, that is, folders can be created under the assets directory.

According to different situations, there are different optimization strategies for resource files. Generally speaking, png resources in res/drawable-hdpi can be compressed.

Picture resource optimization strategy format compression

Use TinyPng or Guetzli for compression. For the use of Guetzli, please see my previous blog post on Mac using the Google image compression tool Guetzli.

Use the WebP file format

When locating Android 3.2 (API level 13) or higher, you can also use the WebP file format to make images instead of using PNG or JPEG files. The WebP format provides lossy compression (such as JPEG) and transparency (such as PNG), but can provide better compression than JPEG or PNG.

Android 4.0 (API level 14) supports lossy compression of WebP format, and Android 4.3 (API level 18) begins to support lossless transparent WebP images.

Use vector graphics

You can use vector graphics to create icons and other scalable media that are independent of resolution. Using these graphics can greatly reduce your APK footprint. Vector images are represented as VectorDrawable objects in Android. Through a VectorDrawable object, a 100-byte file can produce a clear image consistent with the screen size.

However, it takes a long time for the system to render each VectorDrawable object, and larger images take longer to appear on the screen. Therefore, consider using these vector graphics only when displaying small images.

Other strategies

Sometimes we may reuse an image, for example, a picture is only the overall color transformation can use setColorFilter or tint. Try to reduce the use of frame animation, that is a bunch of pictures.

Compress resources

To enable resource compression, set the shrinkResources property to true in the build.gradle file.

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

The resource compressor does not currently remove resources (such as strings, dimensions, styles, and colors) defined in the values/ folder. This is because the Android Resource Packaging tool (AAPT) does not allow the Gradle plug-in to specify predefined versions of resources.

At the same time, we can also specify which resources can be retained.

For example, save the following code in res/raw/keep.xml. The build does not package the file into APK.

Resources has the following properties:

Tools:keep indicates which resources retain tools:discard and which resources need to be excluded from tools:shrinkMode resource compression mode. There are two values: strict and safe. The default is safe.

Optimization strategies for safe and strict:

Safe can be understood simply as safe mode, and it does its best to check the resources that may be used in the code to preserve it to avoid run-time errors.

If your code calls Resources.getIdentifier (), this means that your code will query the resource name based on the dynamically generated string. When you make this call, the resource compressor takes defensive behavior by default, marking all resources with a matching name format as likely to be used and cannot be removed.

String name = String.format ("img_", angle + 1); res = getResources () .getIdentifier (name, "drawable", getPackageName ())

The resource of the img_ prefix is marked as used.

In strict mode, the resources of the img_ prefix will do unused processing, so you need to use tools:keep to manually identify the used.

Remove unused standby resources

We know that google provides international support for our apk, such as drawable resources adapted to different screen resolutions, string resources adapted to different languages, and so on, but in many cases we only need resources that specify resolution and language. At this time, we can use the resConfigs method to configure.

DefaultConfig {/ / for internationalization support, only Chinese resources are packaged. Resource optimization in resConfigs "zh-rCN"} 04 lib

Here we mainly talk about the optimization strategy of dynamic link libraries in lib, that is, SO files. It may be easier to understand if you have NDK development experience.

In order to support different instruction sets, applications may include armeabi, armeabi-v7a, x86 SO files, and so on.

At present, the mainstream models support armeabi-v7a, and armeabi-v7a is compatible with armeabi. So in general development, we only need to use armeabi-v7a for ABI support.

Some SO libraries can be downloaded from the Internet, leaving the burden after the user has installed the application. For which SO files can be loaded on the network, it also depends on the specific business situation.

Beside the point, if the runtime cannot find SO, it will cause the application to crash.

Java.lang.UnsatisfiedLinkError: Couldn't load stlport_shared from loader dalvik.system.PathClassLoader: findLibrary returned null at java.lang.Runtime.loadLibrary (Runtime.java:365) at java.lang.System.loadLibrary (System.java:535) at com.your.app.NativeClass. (Native.java:16)... 63 more Caused by: java.lang.UnsatisfiedLinkError: Library stlport_shared not found at java.lang.Runtime.loadLibrary (Runtime.java:461) at java.lang.System.loadLibrary (System. Java:557) at com.your.app.NativeClass. (Native.java:16). 5 more here The study of "what are the methods of APK structure optimization" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 277

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report