How to reduce the size of your app by 60% in 10 minutes?

How to reduce the size of your app by 60% in 10 minutes?

[[271141]]

The reason why an APP package is large is mainly due to the following files:

  • Code
  • lib
  • so local library
  • Resource files (images, audio, fonts, etc.)

These are the main things you need to lose weight.

1. Delete unused code when packaging

  1. buildTypes {
  2. debug {
  3. ...
  4. shrinkResources true // Whether to remove invalid resource files (if your Debug also needs to be slimmed down)
  5. }
  6. release {
  7. ...
  8. shrinkResources true // Whether to remove invalid resource files
  9. }
  10. }

2. Reduce unnecessary packaging

  1. defaultConfig {
  2. ...
  3. //Packaged language type (language translation)
  4. resConfigs "en" , "de" , "fr" , "it"  
  5. //Packaged folder
  6. resConfigs "nodpi" , "hdpi" , "xhdpi" , "xxhdpi" , "xxxhdpi"  
  7. }

or

  1. android {
  2. ...
  3. splits {
  4. density
  5. enable true  
  6. exclude "ldpi" , "tvdpi" , "xxxhdpi"  
  7. compatibleScreens 'small' , 'normal' , 'large' , 'xlarge'  
  8. //reset()
  9. //include 'x86' , 'armeabi-v7a' , 'mips'  
  10. //universalApk true  
  11. }
  12. }

3.lib

Try not to use too complex libs, lightweight libs are preferred. If your application does not use compatible libraries, you can consider removing the support package.

4. Resource Files

We can find unused resources through the Lint tool (select "Inspect Code..." from the "Analyze" menu in Android Studio)

5. Convert existing images to webP

We can convert images in other formats into webP format through Zhitu or isparta, and isparta can realize batch conversion.

6. Picture related

In Android 5.0 and above, you can use tintcolor to provide only one button image and implement the button inversion effect in the program. The premise is that the content of the image is the same, but the colors of the positive and negative selection buttons are different.

  1. Drawable.setColorFilter(0xffff0000, Mode.MULTIPLY)

In Android 5.0 and above, you can use VectorDrawable and SVG images to replace the original images.

7. Obfuscation

1. Build multiple versions

Add different build types to buildTypes in gradle, and use applicationSuffix and versionNameSuffix to generate multiple versions to run on the same device

Create src/[buildType]/res/ and set different ic_launcher to distinguish different versions

2. Obfuscating parameters

  1. {  
  2. debug { minifyEnabled false }  
  3. release {  
  4. signingConfig signingConfigs.release  
  5. minifyEnabled true    
  6. proguardFiles getDefaultProguardFile( 'proguard-android.txt' ), 'proguard-rules.pro'    
  7. }  
  8. }

minifyEnabled true

  • Whether to enable code shrinking via ProGuard (true to enable)
  • Note that code minification can slow down your builds, so you should avoid using it in debug builds if possible.

Note: Android Studio disables ProGuard when using Instant Run.

proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

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

Tip: For further code shrinking, try using the proguard-android-optimize.txt file located in the same location. It includes the same ProGuard rules, but also includes additional optimizations that perform analysis at the bytecode level (intra-method and inter-method) to further reduce the size of the APK and help it run faster.

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

To add more build variant-specific ProGuard rules, add another proguardFiles property in the corresponding productFlavor code block. For example, the following Gradle file adds flavor2-rules.pro to the flavor2 product flavor. Now flavor2 uses all three ProGuard rules because the rules from the release code block are also applied.

Each time ProGuard builds, it will output the following files: dump.txt describes the internal structure of all class files in the APK. mapping.txt: provides translation between original and obfuscated class, method, and field names. seeds.txt: lists the classes and members that are not obfuscated. usage.txt: lists the code removed from the APK. These files are saved in /build/outputs/mapping/release/.

To fix the error and force ProGuard to keep specific code, add a -keep line to the ProGuard configuration file. For example:

  1. -keeppublicclassMyClass

You can also add [@Keep] to the code you want to keep

(https://developer.android.com/reference/android/support/annotation/Keep.html) annotation. Add @Keep on a class to keep the entire class intact. Add it on a method or field to keep the method/field (and its name) as well as the class name intact. Note that this annotation can only be used when using the Annotation Support Library.

There are many things to consider when using the -keep option; for more information about custom configuration files, read the ProGuard manual. The Troubleshooting chapter outlines other common problems you might encounter when obfuscating code.

Note that the mapping.txt file is overwritten each time you create a release build using ProGuard, so you must be careful to save a copy each time you release a new version. By keeping a copy of the mapping.txt file for each release build, you can debug problems when users submit obfuscated stack traces from an older version of your app.

Every time you add a library, you need to make a release build in time

DexGuard is a software developed by the same team as Proguard. It optimizes code and separates dex files to solve the 65k method limit.

About proguard-android.txt file:

  • -dontusemixedcaseclassnames: Indicates that case-confused class names are not used during obfuscation.
  • -dontskipnonpubliclibraryclasses: Do not skip non-public methods in the library.
  • -verbose: Print detailed information about the obfuscation.
  • -dontoptimize: Do not optimize. Optimization may cause some potential risks and cannot be guaranteed to run properly on all versions of Dalvik.
  • -dontpreverify: Do not preverify.
  • -keepattributes Annotation: Keep annotation parameters.
  • -keep public class com.google.vending.licensing.ILicensingService
  • -keep public class com.android.vending.licensing.ILicensingService:

Indicates that the two classes declared above are not confused.

There are three groups of six keep keywords in proguard.

  1. keep preserves classes and their members to prevent them from being obfuscated or removed.
  2. keepnames preserves classes and their members to prevent them from being obfuscated, but removes them when members are not referenced.
  3. keepclassmembers keeps only the members of the class, preventing them from being obfuscated or removed.
  4. keepclassmembernames keeps only the members in the class, preventing them from being obfuscated, but removes them when the members are not referenced.
  5. keepclasseswithmembers retains classes and members in classes to prevent them from being confused or removed. The premise is that the members in the named class must exist. If they do not exist, they will still be confused.
  6. keepclasseswithmembernames retains classes and members in the class to prevent them from being confused, but they will be removed when the members are not referenced. The premise is that the members in the named class must exist. If they do not exist, they will still be confused.

The difference between keepclasseswithmember and keep keywords:

  • If this class has no native method, then this class will be confused
  1. -keepclasseswithmember class * {
  2. native <methods>;
  3. }
  • Regardless of whether this class has native methods, this class will not be confused
  1. -keep class * {
  2. native <methods>;
  3. }

In addition, you can use APK Analyser to decompose your APK

Android Studio provides a useful tool: APK Analyser. APK Analyser will disassemble your app and let you know which part of the .apk file is taking up a lot of space. Let's take a look at a screenshot of Anti-Theft before it is optimized.

From the output of Apk Analyser, the original size of the app is 3.1MB. After compression by Play Store, it is roughly 2.5MB.

From the screenshot, we can see that there are mainly 3 folders that take up most of the space in the app.

  • classes.dex - This is the dex file, which contains all the bytecode files that will run in your DVM or ART.
  • res - This folder contains all the files under res folder. Most of the time it contains all images, icons and source files, menu files and layouts.

  • resources.arsc —— This file contains all value resources. This file contains all the data in your value directory. Including strings, dimensions, styles, integers, ids, etc.

You have two default obfuscation files.

  • proguard-android-optimize.txt
  • proguard-android.txt

As the file name says, "proguard-android-optimize.txt" is a more aggressive obfuscation option. We use this as the default obfuscation configuration. You can add custom obfuscation configurations in proguard-rules.pro in the /app directory.

  1. release {
  2. //Enable the proguard
  3. minifyEnabled true  
  4. proguardFiles getDefaultProguardFile( 'proguard-android-optimize.txt' ), "proguard-rules.pro"  
  5. //Other parameters
  6. debuggable false  
  7. jniDebuggable false  
  8. renderscriptDebuggable false  
  9. signingConfig playStoreConfig // Add your own signing config
  10. pseudoLocalesEnabled false  
  11. zipAlignEnabled true  

By setting minifyEnabled to true, obfuscation will remove all unused methods and instructions to reduce the classes.dex file.

This is the APK after minify is enabled.

8. AndroidStudio uses lint to remove useless resource files

When using AndroidStudio for App development, we often reference multiple resource files in the project, including images, layout files, and constant reference definitions. As the project version is iterated, each issue of resources will change, leaving some useless resources. At this time, if we manually search one by one, the efficiency will be very low. At this time, we must learn how to use lint in AndroidStudio to remove useless resource files.

Open AndroidStudio in the project and click Analyze -> Run Inspection by Name in the top menu bar as shown below:

Click Run Inspection by Name and a dialog box will pop up. Enter unused resource in the dialog box as shown below:

Then click on the unused resource in the drop-down list. A dialog box will pop up as shown below

<<:  Interpretation of APP development postures in 3 major mobile application methods

>>:  Google launches Byteboard: assessing programmer interviewers based on their work ability

Recommend

List of 7 essential promotion skills for operators!

Promotional methods + operational knowledge = imp...

Panda was once a name that only belonged to the red panda...

Original title: "The Neglected Life of the R...

What wonders will happen when a matter sun and an antimatter sun collide?

This is an answer to a question invited by netize...

Brand promotion, how to formulate a brand portfolio strategy?

What is brand portfolio strategy? It is to system...

How to quickly build a marketing and promotion system for 2B products

In the past two years, the SAAS product market ha...

Memoori: Commercial Office Analytics Market Reached $1.54 Billion in 2017

199IT original compilation According to Memoori&#...

Why can H5 continue to dominate the screen?

No matter which industry you are in, you can alwa...

Identify the three levels of channel fraud from operational data!

How to judge the quality and cunningness of the c...

Baby language enlightenment class

Introduction to baby language enlightenment course...

12 tips to attract new users!

Introduction: User operations are actually divide...

Do figs really have no "flowers"? Take you into the magical world of plants

Produced by: Science Popularization China Author:...