文/ skay

csdn博客:http://blog.csdn.net/sk719887916/article/details/40541163

最近遇到项目从Eclispe迁移到Android studio,以前的Ant自动打包脚本已经兼容不好了,所以用了Gradle实现打渠道包,切换环境等,

Ant打包脚本

 <target name="-release-sign" if="has.keystore">
        <!-- only create apk if *not* a library project -->
        <do-only-if-not-library elseText="Library project: do not create apk...">
            <sequential>
                <property name="out.unaligned.file"
                          location="${out.absolute.dir}/${ant.project.name}-release-unaligned.apk"/>

                <!-- Signs the APK -->
                <echo level="info">Signing final apk with your  apk signer server...</echo>
                <taskdef resource="com/myapk/ant/task/defaults.properties" classpath="${signer.jar}"/>
                <apk-signer
                        server="http://xxx.com/packservice/sign<pre name="code" class="html" style="font-size: 14px; line-height: 26px;">
</pre><p><pre name="code" class="html">" apk="${out.packaged.file}" dest="${out.unaligned.file}" prodkey="${singer.prodkey}" verbose="true" timeout="500" retries="5" /> <!-- Zip aligns the APK --> <zipalign-helper in.package="${out.unaligned.file}" out.package="${out.final.file}"/> <echo level="info">Release Package: ${out.final.file}</echo> </sequential> </do-only-if-not-library> <record-build-info/> </target>

 Gradle

加入配置,签名文件,配置打包生成apk文件名称规则,配置url,配置渠道等

 配置gradle

android {}配置一些关于android的基本配置

1配置依赖关系

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:support-v4:23.2.1'
    compile 'com.android.support:recyclerview-v7:23.2.1'
   ......
}

如果想兼容v4

compile ('com.android.support:recyclerview-v7:22.2.0'){ exclude module: 'support-v4' }

3配置打包方式

signingConfigs {

        release {
            keyAlias props['KEY_ALIAS']
            keyPassword props['KEY_PASSWORD']
            storeFile file(props['KEYSTORE_FILE'])
            storePassword props['KEYSTORE_PASSWORD']
        }

        debug {
            storeFile file('../../debug.keystore')
            storePassword 'you pass'
            keyAlias 'you key'
            keyPassword 'you pass'
        }

    }

加载签名配置文件

Properties props = new Properties()
    props.load(new FileInputStream(file("signing.properties")))

签名文件 signing.properties 配置如下:

KEY_ALIAS = xxxx
KEY_PASSWORD = 你的密码
KEYSTORE_FILE = ../../nide.keystroe (相对路径)
KEYSTORE_PASSWORD =密码

签名你自己可生成,可以直接用eclispe生成的。

三 配置环境



定义线上环境Url

def host_url = "https://xxx.com";

四 配置混淆

开启混淆开关:

minifyEnabled true

开启过滤非引用资源打包 :

shrinkResources true

打开log输出:

buildConfigField "boolean", "LOG_DEBUG", "true"

定义打包方式:

buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            buildConfigField "boolean", "LOG_DEBUG", "false"
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }

        debug {
            minifyEnabled true
            shrinkResources true
            buildConfigField "boolean", "LOG_DEBUG", "true"
            signingConfig signingConfigs.debug
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

编译项目后 会生成buildConfig文件

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  // app id
  public static final String APPLICATION_ID = "com.skay.test";
  public static final String BUILD_TYPE = "debug";
  // 渠道
  public static final String FLAVOR = "dev";
  // 版本
  public static final int VERSION_CODE = 1;
  public static final String VERSION_NAME = "1.0";
  // Fields from the variant
  public static final String APP_ENV = "dev ";
  // host
  public static final String HOST_URL = " http://aaa.com/";
  // Fields from build type: debug
  public static final boolean LOG_DEBUG = true;
}

代码中可以用上面的变量做一些判断。

五 配置打包脚本

 // 指定输出的apk名
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def outputFile = output.outputFile
            // 打包类型
            def buildTypeName = variant.buildType.name
            if (outputFile != null && outputFile.name.endsWith('.apk')) {
                // 包名称
                def flavorName = variant.productFlavors[0].name
                // 版本名称
                def versionName = defaultConfig.versionName
                // 开发环境
                buildConfigField "String", "APP_ENV", "\"${flavorName} \""
                // 修改打包环境的url
                buildConfigField "String", "HOST_URL", "\" ${host_url}\""
                // yourapkname_release_myapk_ver1.0.0_build20130312.apk 输出格式
                def fileName = "${PRODUCT_NAME}_${buildTypeName}_${flavorName}_env${flavorName}_ver${versionName}_build${BUILD_TIME_FORMAT}.apk"

                output.outputFile = new File(outputFile.parent, fileName)
            }
        }
    }

六 切换渠道

//修改渠道号
    productFlavors {

        // 线上版本
         release{
         }

        //开发版本,
        dev {
            host_url = "http://xxxx1.com./"

        }

        //Qa测试版本
        qa{
             host_url = "http://xxx2.com/"
         }

    }

这样我们在打包时 只要你开启你要的那个版本,buildConfig将会修改,输出包就可以了, 不仅切换了Url,而且还制定了渠道版本,非常方便

 六 添加对jar的支持

有时候从eclispe移植过来时,返现jar无法加载,找不到地址

在android {}加入以下配置

sourceSets {
        main {
            jniLibs.srcDir 'libs'
        }

        // Move the tests to tests/java, tests/res, etc...
        instrumentTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }

七 添加对ndk的支持

如果so找不到 请配置对四个不同cpu的支持

在android {}加入以下配置

 defaultConfig {
       .......

      ndk {
       abiFilters "armeabi", "armeabi-v7a", "x86", "mips"
      }
    }

混淆相关:

配置proguard-rules.pro文件

# 混淆时不使用大小写混合,混淆后的类名为小写
# windows下的同学还是加入这个选项吧(windows大小写不敏感)
-dontusemixedcaseclassnames

# 如果应用程序引入的有jar包,并且想混淆jar包里面的class
-dontskipnonpubliclibraryclasses
# 指定不去忽略非公共的库的类的成员
-dontskipnonpubliclibraryclassmembers

# 有了verbose这句话,混淆后就会生成映射文件
# 包含有类名->混淆后类名的映射关系
# 然后使用printmapping指定映射文件的名称
-verbose
-ignorewarnings

# 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).
# 不做预检验,preverify是proguard的四个步骤之一
# Android不需要preverify,去掉这一步可以加快混淆速度
-dontpreverify

# If you want to enable optimization, you should include the following:
# 混淆采用的算法
-optimizations !code/simplification/arithmetic,!code/simplification/cast,!field/*,!class/merging/*
# 设置混淆的压缩比率 0 ~ 7
-optimizationpasses 5
-allowaccessmodification

# 保护代码中的Annotation不被混淆
# 这在JSON实体映射时非常重要,比如fastJson
-keepattributes *Annotation*

# 避免混淆泛型
# 这在JSON实体映射时非常重要,比如fastJson
-keepattributes Signature

# 抛出异常时保留代码行号
-keepattributes SourceFile,LineNumberTable

# Add any project specific keep options here:
# 保留了继承自Activity、Application这些类的子类
# 因为这些子类有可能被外部调用
# 比如第一行就保证了所有Activity的子类不要被混淆
-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.view.View
-keep public class * extends android.app.backup.BackupAgent
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class * extends android.support.v4.app.Fragment
-keep public class * extends android.app.Fragment
-keep public class com.android.vending.licensing.ILicensingService

# For native methods, see http://proguard.sourceforge.net/manual/examples.html#native
# 所有native的方法不能去混淆.
-keepclasseswithmembernames class * {
    native <methods>;
}

# For enumeration classes, see http://proguard.sourceforge.net/manual/examples.html#enumerations
#  枚举类不能去混淆
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

# 某些构造方法不能去混淆
-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

# aidl文件不能去混淆.
# 保留Parcelable序列化的类不能被混淆
-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

# 保留Serializable 序列化的类不被混淆
-keep class * implements java.io.Serializable {
    public *;
}

-keepclassmembers class * implements java.io.Serializable {
   static final long serialVersionUID;
   private static final java.io.ObjectStreamField[] serialPersistentFields;
   !static !transient <fields>;
   private void writeObject(java.io.ObjectOutputStream);
   private void readObject(java.io.ObjectInputStream);
   java.lang.Object writeReplace();
   java.lang.Object readResolve();
}

# 保留Activity中的方法参数是view的方法,
# 从而我们在layout里面编写onClick就不会影响
-keepclassmembers class * extends android.app.Activity {
   public void *(android.view.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*(...);
    public void get*(...);
}

# 对R文件下的所有类及其方法,都不能被混淆
-keepclassmembers class **.R$* {
    *;
}

# 对于带有回调函数onXXEvent的,不能混淆
-keepclassmembers class * {
    void *(**On*Event);
}

常规混淆配置好,可以增加你项目中的混淆了,如数据模型bean,第三方sdk等

-keep class com.baidu.pushsdk.** { *;}
<pre name="code" class="java">-keep class com.mybisniss.mybean.** { *;}

总结:

好了 以上是常用的gradle打包过程中遇到的坑,都能满足你对as的需求了,以后遇到再补充

文/ skay

csdn博客:http://blog.csdn.net/sk719887916/article/details/40541163 请尊重原创

Android Studio Gradle 多渠道自动打包,动态修改HostUrl,签名apk,混淆配置详解的更多相关文章

  1. Android Studio + gradle多渠道打包

    通过工具栏的Build->Build Apk 好像只能打包第一个Module(eclipse里面是Project的概念),怎么多渠道打包呢?目前好像只能一个一个的打 首先在清单文件里设置个变量: ...

  2. Android studio gradle 打包 那些事

    总结了一下 目前觉得比较好用的gradle 和一些打包 经验.放在这里. 首先说下 渠道号 这个概念,我们经常会统计我们的api 访问来源 是来自于那个app store,这有利于 我们针对性的推广. ...

  3. Android studio gradle配置完整版(转)

    Android studio gradle配置完整版https://my.oschina.net/u/1471093/blog/539075 Android studio 自定义打包apk名 - pe ...

  4. Android Studio(十二):打包多个发布渠道的apk文件

    Android Studio相关博客: Android Studio(一):介绍.安装.配置 Android Studio(二):快捷键设置.插件安装 Android Studio(三):设置Andr ...

  5. [转]加速Android Studio/Gradle构建

    加速Android Studio/Gradle构建 android android studio gradle   已经使用Android Studio进行开发超过一年,随着项目的增大,依赖库的增多, ...

  6. Android Studio gradle配置详解

    android gradle配置详解 AppExtension类及其属性 可能大部分人看到AppExtension类会感觉到非常的陌生,其实我们在app中的build.gradle中填写配置信息的时候 ...

  7. android studio gradle 两种更新方法更新

    android studio gradle 两种更新方法更新 第一种.Android studio更新 第一步:在你所在项目文件夹下:你项目根目录gradlewrappergradle-wrapper ...

  8. android studio gradle 更新方法。

    Android studio更新 第一步:在你所在项目文件夹下:你项目根目录gradlewrapper gradle-wrapper.properties   (只要在打开项目的时候选OK,这个文件就 ...

  9. Gradle实现自动打包,签名,自定义apk文件名

    Gradle实现自动打包,签名,自定义apk文件名 什么是签名,签名有什么用 Android APP都需要我们用一个证书对应用进行数字签名,不然的话是无法安装到Android手机上的,平时我们调试运行 ...

随机推荐

  1. Oracle EBS各个模块日志收集的方法

    MSCA(Mobile Supply Chain Application)日志的收集 Reference Note:338291.1 - Howto Enable WMS / MSCA Logging ...

  2. Swift基础之守卫语句guard

    本篇文章翻译自:http://ericcerney.com/swift-guard-statement/原作者:ecerney该语法为swift2.0之后添加的新特性 最开始在Apple的Platfo ...

  3. listener.ora--sqlnet.ora--tnsnames.ora的关系以及手工配置举例(转载:http://blog.chinaunix.net/uid-83572-id-5510.ht)

    listener.ora--sqlnet.ora--tnsnames.ora的关系以及手工配置举例 ====================最近看到好多人说到tns或者数据库不能登录等问题,就索性总结 ...

  4. SSH网上商城---商品详情页的制作

    在前面的博文中,小编分别简单的介绍了邮件的发送以及邮件的激活,逛淘宝的小伙伴都有这样的体会,比如在搜索框中输入连衣裙这个商品的时候,会出现多种多样各种款式的连衣裙,连衣裙的信息包括价格,多少人购买,商 ...

  5. 安卓程序员要拿到5000和1w的薪资,分别需要掌握哪些技术?

    这个是我在逛知乎的时候发现的一个帖子,在这里小小的整理了一下,收集了一些评论,然后我分享出来,希望对自己还有同行有所帮助. 著作权归作者所有. 商业转载请联系作者获得授权,非商业转载请注明出处. 链接 ...

  6. Android实现分享图片和文字的功能

    为了应用的推广,我们经常看到点击分享按钮会出现,比如微博微信等应用的分享二等列表,这是如何实现的呢?这一篇将要详细的介绍. android的实现分享是通过隐式的启动activity. 分享文本 1.a ...

  7. <<精通iOS开发>>第14章例子代码彻底清除警告

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 上一篇我们解决了<<精通iOS开发>> ...

  8. 安卓AsyncTack详解

    我们知道安卓中的UI线程不是线程安全的,即不能在UI线程中进行耗时操作,所以我们通常的做法是开启一个子线程来进行耗时操作,然后将处理后的结果运用Handler机制传递给UI线程,在UI线程中根据处理后 ...

  9. 【Unity Shaders】Vertex & Fragment Shader入门

    写在前面 三个月以前,在一篇讲卡通风格的Shader的最后,我们说到在Surface Shader中实现描边效果的弊端,也就是只对表面平缓的模型有效.这是因为我们是依赖法线和视角的点乘结果来进行描边判 ...

  10. 【一天一道LeetCode】#232. Implement Queue using Stacks

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Impleme ...