Category:Android 性能优化
Article From:


ProGuardIt is a Java class file compressor, optimizer, obfuscation device and pre file validator. The compression step detects and removes unused classes, fields, methods, and attributes. Optimizes the step analysis and optimizes the bytecode of the method. The confusion step rename the remaining classes, fields, and methods with short and meaningless names.These steps make the code smaller, more efficient and more difficult to reverse engineer. The final preverification step adds pre validation information to classes, which are necessary for Java Micro Edition and Java 6 and later.

So we can remove unused classes, fields, methods, and properties by opening the ProGuard, including unused items in the code library, which solves the problem of 64K restrictions in a workable way. At the same time, ProGuard can also optimize bytecode and remove unused generations.Code instructions, and confuse the rest of classes, fields, and methods with short names. This also reduces the size of Apk to a certain extent.

ShrinkResourcesResource compression is provided by Android Plugin for Gradle, which removes unused resources in the application, including unused resources in the library. It can also reduce the size of the Apk.

android {
    buildTypes {
        release {
            minifyEnabled true //Enable code compressionShrinkResources true / / enabled resource compressionProguardFiles getDefaultProguardFile ('pRoguard-android.txt'),''// confusing rule file configuration}}}

  • getDefaultProguardFile(‘proguard-android.txt’) 
    This configuration is meant to get the default ProGuard settings from the Android SDK tools/proguard/ folder. Using proguard-android-optimize.txt can further compress the generation.The code also includes other optimizations to perform analysis at the bytecode level (within and between methods), which can further reduce the size of APK and help speed up its operation.
    You can add custom rules in this file, which is in the same directory as build.gradle.

ProGuardOutput documents and uses:
After the completion of the confusion process, the following documents will be generated.
Explain the internal structure of all class files in APK. It
Provides conversion between primitive and confused classes, methods, and field names. It
List the classes and members that have not been confused. It
List the code removed from the APK. It
These files are stored in the /build/outputs/mapping/release/ directory.

Special attention is needed here: after each release edition is compiled, it is best to add these files to the GIT version library, because the files are covered every time after the Release compilation is compiled.

ProGuard configuration instructions

Save configuration (i.e., do not deal with configuration content).

-keep [,modifier,…] class_specification 
Specifies the class and class members (fields and methods) to be retained.

-keepclassmembers [,modifier,…] class_specification 
Specify the class members to retain if their classes are also preserved. For example, you might want to keep all the serialized fields and classes that implement the Serializable interface.

-keepclasseswithmembers [,modifier,…] class_specification 
Specifies the class and class members to be retained, provided that all specified class members exist. For example, you may want to keep all applications that have main methods without explicit listing.

-keepnames class_specification 
-keepAbbreviations that allow class_specification
Specifies the name of the class and class members to be saved (if they are not deleted at the compression stage). For example, you may want to keep all the class names of the classes that implement the Serializable interface, so that the code to be processed is compatible with any original serialization class. Classes that are not used at all can still be deletedExcept. It is only applicable to confusion.

-keepclassmembernames class_specification 
–keepclassmembersAbbreviations, allowhrinking class_specification
Specifies the class members who want to save their names if they are not deleted at the compression stage. For example, when dealing with libraries compiled by JDK 1.2 or older versions, you may want to retain the name of the internal class $method, so when processing the application with the processed library, the obfuscation can detect it again (Although ProGuard itself does not need this). It is only applicable to confusion.

-keepclasseswithmembernames class_specification 
–keepclasseswithmembernamesAbbreviations that allow class_specification
Specifies the class and class member to retain its name, provided that all specified class members exist after the contraction phase. For example, you may want to retain all native method names and their class names so that the processed code can still be linked to the library code. Local methods that are not used at all can still be deletedExcept. If a class file is used, but its native method is not, its name will still be obscured. It is only applicable to confusion.

-printseeds [filename] 
Specifies that classes and class members that are matched by various protection options are listed thoroughly. A list is printed to a standard output or a given file. This list can be used to verify whether the expected class members are found, especially if you use wildcards. For example, you might want to list all applications or all reserved applets.


Specify uncompressed class files. It
-printusage {filename} 
Specify the class files that need to list dead code. The unused code of the application can be listed. It is only suitable for compression. It
-whyareyoukeeping {class_specification} 
Specifies the details of printing the reason for the keep of the given class and class member in the compression step. It is only suitable for compression.


Specifies that the input class file is not optimized. By default, optimization is enabled; all methods are optimized at bytecode level.

-optimizations optimization_filter 
Specifies the optimization that is enabled and disabled at a finer grained level. It is only suitable for optimization. This is an expert option.

-optimizationpasses n 
Specifies the number of optimizations to be carried out. By default, one way is executed. A number of passes may lead to further improvements. If no improvement is found after the optimization is passed, the optimization is finished. It is only suitable for optimization.

-assumenosideeffects class_specification 
Specifies a method without any side effects (except the value may be returned). In the optimization step, ProGuard will delete calls to these methods, if you can make sure that no return values are used. For example, you can specify method System.out () to delete log records with this option.Code。 Note that this option is only suitable for optimization. Do not use this option unless you know clearly how this method works.

Specifies that access modifiers for classes and class members can be extended during processing. This can improve the result of the optimization step.

The specified interfaces may be merged, even if their implementation classes do not implement all interface methods. This can reduce the size of the output by reducing the total number of classes.


-dontobfuscate Class file that does not confuse input
-obfuscationdictionary {filename} Use the keywords in the given file as the name of the method to be confused.
-overloadaggressively Application of intrusive heavy load
-useuniqueclassmembernames Determine the name of the unified confusion class to increase confusion.
-flattenpackagehierarchy {package_name} Repackage all renamed packages and put them in a given single package.
-repackageclass {package_name} Repackage all renamed class files in a given single package.
-dontusemixedcaseclassnames Confusion does not produce a variety of class names
-keepattributes {attribute_name,…} Protect given optional attributes, such as LineNumberTable, LocalVariableTable, SourceFile, Deprecated, Synthetic, Signature, and INnerClasses.
-renamesourcefileattribute {string} Set a given string constant in the source file

Wildcards can be used in the configuration process. The description of wildcards is as follows.

wildcard Explain
? Match any single character.
* Matches any character except the package delimiter or directory separator.
** Match the name of any character

10:47:34.635 [ERROR] [system.err] Warning: com.kennyc.view.MultiStateView$1: can't find referenced method 'com.kennyc.view.MultiStateView$ViewState[] values()' in program class com.kennyc.view.MultiStateView$ViewState
10:47:34.636 [ERROR] [system.err] Warning: com.kennyc.view.MultiStateView$1: can't find referenced field 'com.kennyc.view.MultiStateView$ViewState LOADING' in program class com.kennyc.view.MultiStateView$ViewState

The content of the configuration can be solved as follows:

-keep class com.kennyc.**

The classes in AndroidMainfest are not confused. The four components and the subclasses of the Application and all the class default under the Framework layer will not be confused, and all the default configurations provided by Android have. The following is Android SDThe default ProGuard configuration in K, that is, the content of proguard-android.txt.

# This is a configuration file for ProGuard.


# Optimization is turned off by default. Dex does not like code run
# through the ProGuard optimize and preverify steps (and performs some
# of these optimizations on its own).
# Note that if you want to enable optimization, you cannot just
# include optimization flags in your own project configuration file;
# instead you will need to point to the
# "proguard-android-optimize.txt" file instead of this one from your
# file.

-keepattributes *Annotation*
-keep public class
-keep public class

# For native methods, see
-keepclasseswithmembernames class * {
    native <methods>;

# keep setters in Views so that animations can still work.
# see
-keepclassmembers public class * extends android.view.View {
   void set*(***);
   *** get*();

# We want to keep methods in Activity that could be used in the XML attribute onClick
-keepclassmembers class * extends {
   public void *(android.view.View);

# For enumeration classes, see
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);

-keepclassmembers class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator CREATOR;

-keepclassmembers class **.R$* {
    public static <fields>;

# The support library contains references to newer platform versions.
# Don't warn about those in case this app is linking against an older
# platform version.  We know about them, and they are safe.

# Understand the @Keep support annotation.
-keep class

-keep class * {*;}

-keepclasseswithmembers class * { <methods>;

-keepclasseswithmembers class * { <fields>;

-keepclasseswithmembers class * { <init>(...);

Enumerate the confusing configuration of some libraries

##---------------Begin: proguard configuration for Twitter  ----------
-dontwarn com.squareup.okhttp.**
-dontwarn rx.**
-dontwarn retrofit.**
-keepattributes Signature
-keepattributes *Annotation*
-keep class com.squareup.okhttp.** { *; }
-keep interface com.squareup.okhttp.** { *; }
-keep class retrofit.** { *; }
-keepclasseswithmembers class * {
    @retrofit.http.* <methods>;
##---------------End: proguard configuration for Twitter  ----------


##---------------Begin: proguard configuration for Gson  ----------
# Gson uses generic type information stored in a class file when working with fields. Proguard
# removes such information by default, so configure it to keep all of it.
-keepattributes Signature

# For using GSON @Expose annotation
-keepattributes *Annotation*

# Gson specific classes
-keep class sun.misc.Unsafe { *; }
#-keep class** { *; }

# Application classes that will be serialized/deserialized over Gson
-keep class** { *; }

# Prevent proguard from stripping interface information from TypeAdapterFactory,
# JsonSerializer, JsonDeserializer instances (so they can be used in @JsonAdapter)
-keep class * implements
-keep class * implements
-keep class * implements
##---------------End: proguard configuration for Gson  ----------


##---------------Begin: proguard configuration for Glide  ----------
-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
##---------------End: proguard configuration for Glide  ----------


##---------------Begin: proguard configuration for EventBus  ----------
-keepattributes *Annotation*
-keepclassmembers class ** {
    @org.greenrobot.eventbus.Subscribe <methods>;
-keep enum org.greenrobot.eventbus.ThreadMode { *; }

# Only required if you use AsyncExecutor
#-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
#    <init>(java.lang.Throwable);
##---------------End: proguard configuration for EventBus  ----------


##---------------Begin: proguard configuration for Paper  ----------
#1.Keep data classes:
-keep class** { *; }
#2.alternatively you can implement Serializable for all your data classes and keep all of them using:
#-keep class * implements { *; }
##---------------End: proguard configuration for Paper  ----------


##---------------Begin: proguard configuration for retrofit2  ----------
# Platform calls Class.forName on types which do not exist on Android to determine platform.
-dontnote retrofit2.Platform
# Platform used when running on Java 8 VMs. Will not be used at runtime.
-dontwarn retrofit2.Platform$Java8
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain declared checked exceptions for use by a Proxy instance.
-keepattributes Exceptions
##---------------End: proguard configuration for retrofit2  ----------

-assumenosideeffects class android.util.Log {  
    public static *** v(...);  
    public static *** i(...);  
    public static *** d(...);  
    public static *** w(...);  
    public static *** e(...);