zoukankan      html  css  js  c++  java
  • AndroidStudio 混淆打包

    AndroidStudio中的项目可以用compile的形式引入github上的开源项目,可以引用module,而不一定都要用libs文件夹中添加jar包的形式。在最终realease打包时,混淆的设置是比较重要的,否则会导致生成的包有很多功能不能正常使用。下面列举一个基本的app的build.gradle和混淆文件。并注意,混淆打包后的apk文件大小会比不使用混淆要小。

    在app根目录下设置build.gradle和混淆文件,然后把混淆选项写入混淆文件就可以。虽然app项目中可能引用了一些module,但这些module工程可以不定义自己的混淆,我的工程目录结构如下:

    其中app是应用主模块,引用剩余的module,被引用module的build.gradle中都使用默认的设置不启用混淆:

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

    在主目录的build.gradle:

    apply plugin: 'com.android.application'
    
    def releaseTime() {
        return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC"))
    }
    
    repositories {
        maven {
            url 'https://oss.sonatype.org/content/repositories/snapshots'
        }
    }
    android {
        compileSdkVersion 22
        buildToolsVersion '22.0.1'
        defaultConfig {
            applicationId "com.*****.****" //自己的applicationId
            minSdkVersion 14
            targetSdkVersion 19
            versionCode 1
            versionName "1.0"
        }
        //执行lint检查,有任何的错误或者警告提示,都会终止构建,我们可以将其关掉。
        lintOptions {
            abortOnError false
        }
    
    
        //签名
        signingConfigs {
            debug {
    
            }
            release {// 自己的签名文件
                storeFile file("doc/****.jks") 
                storePassword "******"
                keyAlias "******"
                keyPassword "******"
            }
        }
    
        buildTypes {
            debug {
                // 显示Log
                buildConfigField "boolean", "LOG_DEBUG", "true"
                versionNameSuffix "-debug"
                minifyEnabled false
                zipAlignEnabled false
                shrinkResources false
                signingConfig signingConfigs.debug
            }
    
            release {
                // 不显示Log
                buildConfigField "boolean", "LOG_DEBUG", "false"
                //混淆
                minifyEnabled true
                //Zipalign优化
                zipAlignEnabled true
    
                // 移除无用的resource文件
                shrinkResources true
                //前一部分代表系统默认的android程序的混淆文件,该文件已经包含了基本的混淆声明,后一个文件是自己的定义混淆文件
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                //签名
                signingConfig signingConfigs.release
    
                applicationVariants.all { variant ->
                    variant.outputs.each { output ->
                        def outputFile = output.outputFile
                        if (outputFile != null && outputFile.name.endsWith('.apk')) {
                            // 输出apk名称为app_v1.0_2015-xx-xx_xxxx.apk
                            //def fileName = "app_v${defaultConfig.versionName}_${releaseTime()}.apk"
                            def fileName = "app_v${defaultConfig.versionName}_${variant.productFlavors[0].name}.apk"
                            output.outputFile = new File(outputFile.parent, fileName)
                        }
                    }
                }
            }
        }
        //渠道Flavors,配置不同风格的app,友盟渠道统计时用到
        productFlavors {
            "offical" {}
            "360" {}
            yingyongbao {}
            wandoujia {}
            baidu {}
            "91" {}
        }
    
    }
    
    
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile project(':appsdk')
        compile 'com.jakewharton:butterknife:7.0.1'
        //compile 'com.faradaj:blur-behind:1.1'
        compile 'com.github.ksoichiro:android-observablescrollview:1.6.0'
        compile 'com.nineoldandroids:library:2.4.0'
        compile 'in.srain.cube:ultra-ptr:1.0.10'
        compile 'com.android.support:cardview-v7:22.1.0'
        compile project(':multi-image-selector')
    }
    proguard-rules.pro文件中则定义了项目的混淆选项,定义如下:
    # Add project specific ProGuard rules here.
    # By default, the flags in this file are appended to flags specified
    # in D:Androidsdk/tools/proguard/proguard-android.txt
    # You can edit the include path and order by changing the proguardFiles
    # directive in build.gradle.
    #
    # For more details, see
    #   http://developer.android.com/guide/developing/tools/proguard.html
    
    # Add any project specific keep options here:
    
    # If your project uses WebView with JS, uncomment the following
    # and specify the fully qualified class name to the JavaScript interface
    # class:
    -keepclassmembers class fqcn.of.javascript.interface.for.webview {
       public *;
    }
    
    #指定代码的压缩级别
    -optimizationpasses 5
    
    #包明不混合大小写
    -dontusemixedcaseclassnames
    
    #不去忽略非公共的库类
    -dontskipnonpubliclibraryclasses
    
     #优化  不优化输入的类文件
    -dontoptimize
    
     #预校验
    -dontpreverify
    
     #混淆时是否记录日志
    -verbose
    
     # 混淆时所采用的算法
    -optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
    
    #保护注解
    -keepattributes *Annotation*
    
    # 保持哪些类不被混淆
    -keep public class * extends android.app.Fragment
    -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 public class com.android.vending.licensing.ILicensingService
    #如果有引用v4包可以添加下面这行
    -keep public class * extends android.support.v4.app.Fragment
    
    
    #忽略警告
    -ignorewarning
    
    ##记录生成的日志数据,gradle build时在本项目根目录输出##
    #apk 包内所有 class 的内部结构
    -dump proguard/class_files.txt
    #未混淆的类和成员
    -printseeds proguard/seeds.txt
    #列出从 apk 中删除的代码
    -printusage proguard/unused.txt
    #混淆前后的映射
    -printmapping proguard/mapping.txt
    ########记录生成的日志数据,gradle build时 在本项目根目录输出-end######
    
    #如果引用了v4或者v7包
    -dontwarn android.support.**
    
    ####混淆保护自己项目的部分代码以及引用的第三方jar包library-end####
    
    
    
    #保持 native 方法不被混淆
    -keepclasseswithmembernames class * {
        native <methods>;
    }
    
    #保持自定义控件类不被混淆
    -keepclasseswithmembers class * {
        public <init>(android.content.Context, android.util.AttributeSet);
    }
    
    #保持自定义控件类不被混淆
    -keepclassmembers class * extends android.app.Activity {
       public void *(android.view.View);
    }
    
    -keep public class * extends android.view.View {
        public <init>(android.content.Context);
        public <init>(android.content.Context, android.util.AttributeSet);
        public <init>(android.content.Context, android.util.AttributeSet, int);
        public void set*(...);
    }
    
    #保持 Parcelable 不被混淆
    -keep class * implements android.os.Parcelable {
      public static final android.os.Parcelable$Creator *;
    }
    
    #保持 Serializable 不被混淆
    -keepnames class * implements java.io.Serializable
    
    #保持 Serializable 不被混淆并且enum 类也不被混淆
    -keepclassmembers class * implements java.io.Serializable {
        static final long serialVersionUID;
        private static final java.io.ObjectStreamField[] serialPersistentFields;
        !static !transient <fields>;
        !private <fields>;
        !private <methods>;
        private void writeObject(java.io.ObjectOutputStream);
        private void readObject(java.io.ObjectInputStream);
        java.lang.Object writeReplace();
        java.lang.Object readResolve();
    }
    
    #保持枚举 enum 类不被混淆
    -keepclassmembers enum * {
      public static **[] values();
      public static ** valueOf(java.lang.String);
    }
    
    -keepclassmembers class * {
        public void *ButtonClicked(android.view.View);
    }
    
    #不混淆资源类
    -keepclassmembers class **.R$* {
        public static <fields>;
    }
    
    #避免混淆泛型 如果混淆报错建议关掉
    #-keepattributes Signature
    
    #移除Log类打印各个等级日志的代码,打正式包的时候可以做为禁log使用,这里可以作为禁止log打印的功能使用,另外的一种实现方案是通过BuildConfig.DEBUG的变量来控制
    #-assumenosideeffects class android.util.Log {
    #    public static *** v(...);
    #    public static *** i(...);
    #    public static *** d(...);
    #    public static *** w(...);
    #    public static *** e(...);
    #}
    
    #############################################################################################
    ########################                 以上通用           ##################################
    #############################################################################################
    
    #######################     常用第三方模块的混淆选项         ###################################
    #gson
    #如果用用到Gson解析包的,直接添加下面这几行就能成功混淆,不然会报错。
    -keepattributes Signature
    # Gson specific classes
    -keep class sun.misc.Unsafe { *; }
    # Application classes that will be serialized/deserialized over Gson
    -keep class com.google.gson.** { *; }
    -keep class com.google.gson.stream.** { *; }
    
    #mob
    -keep class android.net.http.SslError
    -keep class android.webkit.**{*;}
    -keep class cn.sharesdk.**{*;}
    -keep class com.sina.**{*;}
    -keep class m.framework.**{*;}
    -keep class **.R$* {*;}
    -keep class **.R{*;}
    -dontwarn cn.sharesdk.**
    -dontwarn **.R$*
    
    #butterknife
    -keep class butterknife.** { *; }
    -dontwarn butterknife.internal.**
    -keep class **$$ViewBinder { *; }
    
    -keepclasseswithmembernames class * {
        @butterknife.* <fields>;
    }
    
    -keepclasseswithmembernames class * {
        @butterknife.* <methods>;
    }
    
    ######引用的其他Module可以直接在app的这个混淆文件里配置
    
    # 如果使用了Gson之类的工具要使被它解析的JavaBean类即实体类不被混淆。
    -keep class com.matrix.app.entity.json.** { *; }
    -keep class com.matrix.appsdk.network.model.** { *; }
    
    #####混淆保护自己项目的部分代码以及引用的第三方jar包library#######
    #如果在当前的application module或者依赖的library module中使用了第三方的库,并不需要显式添加规则
    #-libraryjars xxx
    #添加了反而有可能在打包的时候遭遇同一个jar多次被指定的错误,一般只需要添加忽略警告和保持某些class不被混淆的声明。
    #以libaray的形式引用了开源项目,如果不想混淆 keep 掉,在引入的module的build.gradle中设置minifyEnabled=false
    -keep class com.nineoldandroids.** { *; }
    -keep interface com.nineoldandroids.** { *; }
    -dontwarn com.nineoldandroids.**
    # 下拉刷新
    -keep class in.srain.cube.** { *; }
    -keep interface in.srain.cube.** { *; }
    -dontwarn in.srain.cube.**
    # observablescrollview:tab fragment
    -keep class com.github.ksoichiro.** { *; }
    -keep interface com.github.ksoichiro.** { *; }
    -dontwarn com.github.ksoichiro.**

    然后执行build的release打包,会在app目录下生成一个proguard文件夹,里面有混淆前后文件的映射信息等文本文件,以后bug定位就靠它了:

     
  • 相关阅读:
    软工小白菜的团队介绍和采访
    团队作业第二次——团队Github实战训练
    团队作业第一次—团队展示和项目展示
    week5:Technology: Internets and Packets
    week3:History: The Web Makes it Easy to Use
    week2:History: The First Internet
    week4:History: Commercialization and Growth
    week1:History: Dawn of Electronic Computing
    第二日会议博客
    第一日会议博客
  • 原文地址:https://www.cnblogs.com/permanent2012moira/p/5126276.html
Copyright © 2011-2022 走看看