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 is the Android compression step?

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

Share

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

What is the Android compression step, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

Brief introduction

As the project iterates, the amount of code and resource files increases. Then it will appear that the packaged APK file is getting bigger and bigger, if suddenly one day your boss or leader asks you to optimize the APK size, you do not know how to optimize it, it is a bit unreasonable, in this article let's analyze and optimize the APK size together.

Analyze APK resource occupancy

Note:

I found a popular open source project in GitHub. If you need it, you can click and download it and try it yourself.

AS Build/Analyze APK for direct use of analysis tools

From the figure above, we can see that assets > classes.dex > res > lib where resource files occupy the most.

Let's take a look at how to reduce the APK size.

Eight steps to optimize APK Volume

1. Convert the picture to webp format

Webp concept

WebP is a picture file format that provides both lossy compression and lossless compression, which is derived from the video coding format VP8. WebP was originally released in 2010 with the goal of reducing file size but achieving the same picture quality as JEPG format, hoping to reduce the time it takes to send pictures on the web. On November 8, 2011, Google began to allow WebP to support lossless compression and transparent colors.

According to Google's earlier tests, WebP's lossless compression is 45% smaller than the PNG files found on the network, and even if these PNG files have been processed with PNGCRUSH and PNGOUT, WebP can still reduce the file size by 28%. For now, Webp can reduce image size by an average of 70 per cent. WebP is the trend of picture format in the future.

PNG / JPG to Webp

Right click on the picture or folder and select Convert to Webp format to compress the png / jpg image into webp format.

In the end, we only reduced less than 200 kb, it is possible that the project image resources are not too big, just caused by too many small pictures.

Application scenarios and advantages

Client software, embedded with Chromium-based webview, the web pages applied in this kind of browsers can use WebP format completely to improve the loading and rendering speed, regardless of compatibility.

Program developed with node-webkit, using WebP can reduce the size of the file package.

For mobile applications or web games, the interface requires a large number of images, which can be embedded in WebP decoding packets, which can save user traffic and improve access speed:

For PNG images, WebP is 45% smaller than PNG.

two。 Removal of multilingualism

Add in app/build.gradle

Android {... DefaultConfig {. / / only English resConfigs "en"}}

Here we found a reduction of about 200 kb.

3. Remove unnecessary so libraries

By decompiling the Wechat version of Android, we know that Wechat only adapts to the armeabi-v7a architecture, so let's delete the support of other libraries.

Android {... DefaultConfig {... Ndk {/ / set supported SO library schema abiFilters "armeabi-v7a"}

It has been optimized by about 600 kb. Continue.

4. Remove unwanted resources Link check (carefully delete)

Concept

Lint is a code scan analysis tool provided by Android Studio, which can help us find code structure / quality problems and provide some solutions, and this process does not require our handwritten test cases. With more than one iterative version of the code, it is easy to leave some useless code and resource files behind, which we can use Lint to clear.

How to use Link check

Open the AS tool and find Analyze > Run Inspection By Name > unused resources

Optimize

It is found that our link has optimized about 700 kb to continue.

Be careful

Because link is to check whether there are references to determine whether resources are used, then if it is done in this way, you must be careful when deleting it.

/ / obtain the resource id dynamically without using R.xx.xx directly, then the resource represented by the id will be considered unused (similar to the reflection class that cannot be confused) int indetifier = getResources () .getIdentifier ("img_bubble_receive", "drawable", getPackageName ()); getResources () .getDrawable (indetifier)

5. Turn on confusion

Optimized about 1.7m to continue.

6. Remove unwanted resource shinkResource

Enable shinkResource = true

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

It is possible that link has removed useless resources, so it is not being optimized.

7. Enable deletion of useless resources (strict mode and normal mode)-this can not be tested here, you can test the effect.

The normal mode is the custom mode.

If you have specific resources that you want to retain or discard, create a XML file in your project that contains tags, specify each resource to retain in the tools:keep attribute, and specify each resource to discard in the tools:discard attribute. Both properties accept a comma-separated list of resource names. You can use the asterisk character as a wildcard.

For example:

Save the file in the project resource, for example, in res/raw/keep.xml. The build does not package the file into APK.

Specifying resources to discard may seem stupid because you could have deleted them, but this can be useful when using build variants. For example, if you know that a given resource is ostensibly used in the code (and therefore will not be removed by the compressor) but is not actually used for a given build variant, you can put all resources into a common project directory and create a different keep.xml file for each build variant. The build tool may also fail to identify resources correctly as needed, because the compiler adds an inline resource ID, and the resource analyzer may not know the difference between the resources that are actually referenced and the integer values in code that happen to have the same value.

Strict mode

Under normal circumstances, the resource compressor can accurately determine whether the system is using resources. However, if your code calls Resources.getIdentifier () (or any of your libraries make this call-the AppCompat library executes the call), 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.

For example, the following code marks all resources with the img_ prefix as used.

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

The resource compressor also browses the code and all string constants in various res/raw/ resources, looking for resource URLs in a format similar to file:///android_res/drawable//ic_plus_anim_016.png. If it finds similar strings, or finds other strings that appear to be available to build similar URLs, it will not remove them.

These are examples of secure compression modes that are enabled by default. However, you can deactivate this "preparedness" approach and specify that the resource compressor retains only the resources it determines to be used. To do this, set shrinkMode to strict in the keep.xml file, as follows:

If you do enable strict compression mode, and your code references resources that contain dynamically generated strings, as shown above, you must manually reserve those resources using the tools:keep property.

8. AndResGuard Wechat resource compression scheme

What is AndResGuard?

AndResGuard is a tool for reducing the size of APK, and its principle is similar to Java Proguard, but only for resources. It shortens an otherwise lengthy resource path, such as turning res/drawable/wechat into r/d/a.

Why use AndResGuard

In previous development, we usually only confused the code, but the resource files were exposed to others, and all the file names under the res folder were too readable.

The effect after use

Configuration of AndResGuard

Add dependencies for plug-ins in build.gradle under the project root directory:

Dependencies {classpath 'com.tencent.mm:AndResGuard-gradle-plugin:1.2.16'}

In the app directory, create the and_res_guard.gradle file.

Apply plugin: 'AndResGuard' andResGuard {mappingFile = null use7zip = true useSign = true keepRoot = false compressFilePattern = ["* .png", "* .jpg", "* .jpeg", "* .gif", "resources.arsc"] whiteList = [/ / your icon "R.drawable.icon", / / for fabric "R.string.com.crashlytics.*", / / for umeng update "R.string.tbaked *", "R.layout.tbaked *" "R.drawable.tbaked *", "R.drawable.u1*", "R.drawable.u2*", "R.color.tbaked *", / / umeng share for sina "R.drawable.sina*", / / for google-services.json "R.string.google_app_id", "R.string.gcm_defaultSenderId", "R.string.default_web_client_id", "R.string.ga_trackingId", "R.string.firebase_database_url" "R.string.google_api_key", "R.string.google_crash_reporting_api_key", / / Friendship "R.string.umeng*", "R.string.UM*", "R.layout.umeng*", "R.drawable.umeng*", "R.id.umeng*", "R.anim.umeng*", "R.color.umeng*", "R.style.UM*", "R.style.umeng*" / / melting cloud "R.drawable.u*", "R.drawable.rcrack *", "R.string.rcbrush *", "R.layout.rcrack *", "R.color.rcrack *", "R.style.rcrack *", "R.style.rcations *", "R.dimension.rcations *"] sevenzip {artifact = 'com.tencent.mm:SevenZip:1.2.10'}}

In the build.gradle file under the app module, add:

Apply from: 'and_res_guard.gradle'

After packing, the effect picture

Resources have been compressed by about 1m.

The larger the size of the project, the more resources, the more obvious the effect.

If you use Link to delete resources, you must be careful to make backups in advance.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

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: 0

*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