Android Studio: ProGuard 혼동 구성

15043 단어 Android_Studio
Android Studio에서 proguard-rules를 구성할 수 있습니다.pro는 쉽게 해독되지 않도록 생성된 apk와jar를 암호화합니다.(첨부: 해결 방법)
Android Studio에서 Module을 만들면 proguard-rules가 자동으로 생성됩니다.pro 파일, 필요한 규칙을 추가하면 되고,build를 설정해야 합니다.gradle, 혼동 기능을 시작합니다.
    buildTypes {
        debug {
            buildConfigField "boolean", "LOG_DEBUG", "true"
            // VersionName  
            versionNameSuffix "-debug"
            minifyEnabled false
            zipAlignEnabled false
            shrinkResources false
        }
        release {
            //    log
            buildConfigField "boolean", "LOG_DEBUG", "false"
            //   
            minifyEnabled true
            // Zipalign  
            zipAlignEnabled true
            //      resource
            shrinkResources true
            //     
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

그 중에서release 부분은 혼동을 열기 위해 설정되어 있으며,release를 포장할 때 혼동이 발생할 수 있음을 보증합니다.debug가 혼동되지 않습니다. 그렇지 않으면 디버깅할 수 없습니다.
혼동된jar가 필요하면 라이브러리 형식의moudle에proguard-rules를 설정해야 합니다.pro 및build.gradle, 생성 후 build\intermediates\bundles\release에서 혼동된jar를 얻을 수 있습니다.
ProGuard 소개
ProGuard는 자바 클래스의 코드를 압축(Shrink), 최적화(Optimize), 혼동(Obfuscate), 예검(Preveirfy)할 수 있다.
  • 압축(Shrink): 사용하지 않은 클래스, 필드, 방법 및 속성을 감지하고 삭제합니다.
  • 최적화(Optimize): 바이트 코드를 최적화하고 쓸모없는 명령을 제거합니다.
  • 혼동(Obfuscate): a, b, c 등 무의미한 이름을 사용하여 클래스, 필드와 방법의 이름을 바꿉니다.
  • 예찰(Preveirfy): 주로 자바 플랫폼에서 처리된 코드를 예찰한다.

  • 일반적인 규칙은 다음과 같습니다.
    기울임꼴은 설정해야 하는 매개변수를 나타내고 []의 내용은 선택적 구성을 나타냅니다.
  • 【-assumenosideeffects class_specification】

  • Assume that the specified methods don’t have any side effects, while optimizing.
               ,  proguard            remove  。  system.out.println   Log.v  。
    
  • 【-dontwarn [class_filter]】

  • Don’t warn about unresolved references at all.
  • 【-dump [filename]】

  • Write out the internal structure of the processed class files, to the standard output or to the given file.
  • 【-keep [,modifier,…] class_specification】

  • Preserve the specified classes and class members.
  • 【-keepattributes [attribute_filter]】

  • Preserve the given optional attributes; typically Exceptions , InnerClasses , Signature , Deprecated , SourceFile , SourceDir , LineNumberTable , LocalVariableTable , LocalVariableTypeTable , Synthetic , EnclosingMethod , and *Annotation* .
  • 【-keepclasseswithmembernames class_specification】

  • Preserve the names of the specified classes and class members, if all of the specified class members are present (after the shrinking step).
  • 【-keepclassmembers [,modifier,…] class_specification】

  • Preserve the specified class members, if their classes are preserved as well.
  • 【-keepnames class_specification】

  • Preserve the names of the specified classes and class members (if they aren’t removed in the shrinking step).
  • 【-libraryjars class_path】

  • Specifies the library jars (or wars, ears, zips, or directories).
          ,  android-support-v4。
    
  • 【-optimizationpasses n】

  • The number of optimization passes to be performed.
  • 【-optimizations optimization_filter】

  • The optimizations to be enabled and disabled.
  • 【-printmapping [filename]】

  • Print the mapping from old names to new names for classes and class members that have been renamed, to the standard output or to the given file.
  • 【-printseeds [filename]】

  • List classes and class members matched by the various -keep options, to the standard output or to the given file.
  • 【-printusage [filename]】

  • List dead code of the input class files, to the standard output or to the given file.
    ProGuard의 일반적인 구성
    androidsdk의 /sdk/tools/proguard/proguard-android.txt에서 기본적인 혼동 설정을 제공했기 때문에proguard-rules가 필요하지 않습니다.pro에서 설정을 반복합니다.
    sdk에서 제공하는proguard-android.txt에서 제공하는 기본 설정 설명은 안드로이드:proguard-android를 참고하십시오.txt 해석.
    이외에proguard-rules가 필요합니다.pro에 추가되는 일반적인 구성은 다음과 같습니다.
    ########################    ########################
    
    #         
    -optimizationpasses 5
    
    #          
    -optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
    
    #         ,gradle build          
    #apk      class      
    -dump class_files.txt
    #        
    -printseeds seeds.txt
    #    apk       
    -printusage unused.txt
    #       
    -printmapping mapping.txt
    
    #  log  
    -assumenosideeffects class android.util.Log {
        public static *** v(...);
        public static *** i(...);
        public static *** d(...);
        public static *** w(...);
        public static *** e(...);
    }
    
    #         
    -keepattributes Signature
    -keepattributes EnclosingMethod
    
    #         class    
    -keep public class * extends android.app.Activity
    -keep public class * extends android.app.Application
    -keep public class * extends android.app.Service
    -keep public class * extends android.content.BroadcastReceiver
    -keep public class * extends android.content.ContentProvider
    -keep public class * extends android.app.backup.BackupAgentHelper
    -keep public class * extends android.preference.Preference
    -keep interface android.support.v4.app.** { *; }
    -keep class android.support.v4.** { *; }
    -keep public class * extends android.support.v4.**
    -keep interface android.support.v7.app.** { *; }
    -keep class android.support.v7.** { *; }
    -keep public class * extends android.support.v7.**
    -keep public class * extends android.app.Fragment
    -keep class * extends android.**{*;}
    
    #   Serializable                  
    -keepclassmembers class * implements java.io.Serializable {
        static final long serialVersionUID;
        private static final java.io.ObjectStreamField[] serialPersistentFields;
        private void writeObject(java.io.ObjectOutputStream);
        private void readObject(java.io.ObjectInputStream);
        java.lang.Object writeReplace();
        java.lang.Object readResolve();
    }
    
    ######################## Module    ########################
    
    ############       jar ############
    
    #   butterknife
    -keepclasseswithmembernames class * {
        @butterknife.* ;
    }
    -keepclasseswithmembernames class * {
        @butterknife.* ;
    }
    -dontwarn butterknife.internal.**
    
    #   AndroidBootstrap
    -keep class com.beardedhen.androidbootstrap.**{*;}
    -dontwarn com.beardedhen.androidbootstrap.**
    
    #         jar
    -keep class com.qq.**
    -dontwarn com.qq.**
    -keep class com.tencent.**
    -dontwarn com.tencent.**
    
    ############             ############
    
    -keepclasseswithmembernames class * {
        public (android.content.Context);
    }
    -keepclasseswithmembernames class * {
        public (android.content.Context, android.util.AttributeSet);
    }
    -keepclasseswithmembernames class * {
        public (android.content.Context, android.util.AttributeSet, int);
    }
    -keepclasseswithmembernames class * {
        public (android.content.Context, android.util.AttributeSet, int, int);
    }
    
    ############            ############
    
    #      
    #-keep class com.test.test.**{*;}
    
    #        public      ,        
    #-keep public interface com.test.test.**{*;}
    #-keep public enum com.test.test.**{*;}
    #-keep public class com.test.test.**{
    #    public *;
    #}
    
    #       Module    ############
    #-dontwarn com.test.test.**

    주의 사항
  • 반사에 사용된 클래스는 혼동해서는 안 되며, JNI 방법은 혼동하지 않음
  • AndroidMainfest의 클래스 불혼동
  • 4대 구성 요소와 Application의 하위 클래스와 Framework 층의 모든 클래스는 기본적으로 혼동되지 않습니다
  • Parcelable의 하위 클래스와Creator 정적 구성원 변수는 혼동되지 않으며 그렇지 않으면android가 발생합니다.os.BadParcelable Exception 예외
  • GSON,fastjson 등 프레임워크를 사용할 때 쓴 JSON 대상 클래스가 혼동되지 않습니다. 그렇지 않으면 JSON을 대응하는 대상
  • 으로 해석할 수 없습니다.
  • 타사 소스 라이브러리를 사용하거나 다른 타사 SDK 패키지를 참조할 경우 혼동 파일에 대응하는 혼동 규칙
  • 을 추가해야 합니다.
  • WEBView에 대한 JS 호출에도 쓰기 인터페이스 방법이 혼동되지 않도록
  • 참고 자료
    공식 소개
  • 안드로이드 스튜디오에서 모듈로 구성된 bulid.gradle과 혼동proguard-rules.pro
  • 안드로이드 ProGuard 혼동 자세히
  • 에서 자주 사용하는 제3자 라이브러리의 혼동 설정은 그 중에서 자주 사용하는 제3자 라이브러리의 혼동 설정을 제공했다. 예를 들어 glide(Google에서 공식적으로 나온 이미지 로딩 라이브러리), stetho(페이스북에서 나온 흑과학기술, Okhttp 프레임워크를 이용하여 Chrome 디스플레이 app 로그와 수거 라이브러리 등 데이터를 지원), Gson(Json에서 POJO로 전환하고 공식적으로 출품한 json 클래식 라이브러리),butterknife(주해 프레임), 10Okio(NIO 기반 흐름), Rxjava10WebView 등.
  • 좋은 웹페이지 즐겨찾기