当用AndroidStudio来进行Android项目开发时,build.gradle就是这个工具的核心部分,所有的依赖,debug/release设置,混淆等都在这里进行配置。
下面就主要来记录下利用buildConfigField来为我们的项目进行动态配置的目的
eg:debug:打印日志,在内网测试,利用签名
release:关闭日志,外网,签名等
先贴出一个完事的build.gradle文件,如下:

apply plugin: 'com.android.application'
apply plugin: 'AndResGuard'//利用微信的资源混淆工具
//apply plugin: 'io.fabric'

buildscript {
repositories {
jcenter()
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
// The Fabric Gradle plugin uses an open ended version to react
// quickly to Android tooling updates
classpath 'io.fabric.tools:gradle:latest.integration'
}
}

repositories {
jcenter()
maven { url 'https://maven.fabric.io/public' }
}
android {
compileSdkVersion 21
buildToolsVersion "22.0.1"

packagingOptions {
exclude 'LICENSE.txt'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/dependencies'
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/dependencies.txt'
exclude 'META-INF/LGPL2.1'
exclude 'META-INF/LICENSE'
exclude 'META-INF/license'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/notice'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/notice.txt'
exclude 'META-INF/README.txt'
exclude 'META-INF/services/javax.annotation.processing.Processor'
exclude '!META-INF/MANIFEST.MF'
exclude 'META-INF/MANIFEST.MF'

}

defaultConfig {
targetSdkVersion 21
// multiDexEnabled true
}

/**
* 这前用上面multiDexEnabled true时,
* 突然在5.0以下的手机上跑不起来,
* 改成下面这种写法就可以了。
*/
dexOptions {
jumboMode true
}

signingConfigs {
release {
try {
storeFile file("../keystore/Het_KeyStore.keystore")//这里替换成你自己项目生成的keystore的存储路径
storePassword "szhittech"
keyAlias "Clife"
keyPassword "szhittechclife"
} catch (ex) {
throw new InvalidUserDataException(ex.toString())
}
}

debug {
try {
storeFile file("../keystore/Het_KeyStore.keystore")
storePassword "szhittech"
keyAlias "Clife"
keyPassword "szhittechclife"
} catch (ex) {
throw new InvalidUserDataException(ex.toString())
}
}
}

buildTypes {
release {
buildConfigField("boolean", "LOG_DEBUG", "false")
buildConfigField "String", "SERVER_HOST", "\"api.clife.cn/\""
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
//是否清理无用资源
shrinkResources true
//是否启用zipAlign压缩
zipAlignEnabled true
pseudoLocalesEnabled true
signingConfig signingConfigs.release
}

debug {
buildConfigField("boolean", "LOG_DEBUG", "true")
buildConfigField "String", "SERVER_HOST", "\"200.200.200.50/\""
minifyEnabled true//true:启用混淆,false:不启用
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
shrinkResources false
zipAlignEnabled true
pseudoLocalesEnabled true
signingConfig signingConfigs.release
}
}

sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
assets.srcDirs = ['assets']
java.srcDirs = ['src']
res.srcDirs = ['res']
jniLibs.srcDirs = ['libs']
}
}

lintOptions {
abortOnError false

}

/* buildTypes{
debug{
signingConfig signingConfigs.HetConfig
}

release {
signingConfig signingConfigs.HetConfig
}
}*/
}
//微信资源混淆工具
andResGuard {
mappingFile = null
use7zip = true
keepRoot = false
// add <yourpackagename>.R.drawable.icon into whitelist.
// because the launcher will get the icon with his name
whiteList = [
"andresguard.tencent.com.andresguard_example.R.drawable.icon",
//https://docs.fabric.io/android/crashlytics/build-tools.html
"andresguard.tencent.com.andresguard_example.R.string.com.crashlytics.*"
]
compressFilePattern = [
"*.png",
"*.jpg",
"*.jpeg",
"*.gif",
"resources.arsc"
]
//修改成本地SDK中zipalign路径
// zipAlignPath = '/Users/sun/Library/Android/sdk/build-tools/21.1.1/zipalign'
zipAlignPath = ' D:\\eclipse\\all_adt-bundle-windows-x86_64-20140321\\adt-bundle-windows-x86_64-20140321\\sdk\\build-tools\\21.1.1\\zipalign'

//替换成本地7zip路径
//sevenZipPath = '/usr/local/bin/7za'
sevenZipPath = 'D:\\2345Soft\\7zip\\7-Zip\\7z'
}

dependencies {
compile fileTree(dir: 'compile-libs', include: '*.jar')
// provided files('../csleep/libs/butterknife-5.1.2.jar')
compile fileTree(dir: 'libs', include: '*.jar')
provided files('../CommonBusiness/build/intermediates/bundles/release/classes.jar')
// provided files('../CommonResource/build/intermediates/bundles/release/classes.jar')
compile project(':CLifeAsr')
compile project(':csleep')
compile project(':CommonResource')
provided files('../ShareSDK/libs/libammsdk.jar')
provided files('../ShareSDK/libs/open_sdk.jar')
provided files('../CommonBusiness/libs/eventbus.jar')
// configurations {
// all*.exclude group: 'com.android.support', module: 'support-v4'
// }

compile('com.crashlytics.sdk.android:crashlytics:2.5.2@aar') { transitive = true; }
}

这个build.gradle只是自己项目中用到的,肯定没有包含所有,也没有哪个项目会在build.gralde中把所有东西都用到。这里只想起个抛砖引玉的作用,这里没有的,google上肯定可以查到的。
下面就只说说build.gradle 中buildTypes中的buildConfigField的作用。
如上:

buildConfigField("boolean", "LOG_DEBUG", "true")
buildConfigField "String", "SERVER_HOST", "\"200.200.200.50/\""
1
2
看下groovy中的源码:

/**
* Adds a new field to the generated BuildConfig class.
*
* <p>The field is generated as: <code><type> <name> = <value>;</code>
*
* <p>This means each of these must have valid Java content. If the type is a String, then the
* value should include quotes.
*
* @param type the type of the field
* @param name the name of the field
* @param value the value of the field
*/
public void buildConfigField(
@NonNull String type,
@NonNull String name,
@NonNull String value) {
ClassField alreadyPresent = getBuildConfigFields().get(name);
if (alreadyPresent != null) {
logger.info(
"BuildType(${getName()}): buildConfigField '$name' value is being replaced: ${alreadyPresent.value} -> $value");
}
addBuildConfigField(AndroidBuilder.createClassField(type, name, value));
}

一目了然,这个方法接收三个非空的参数,第一个:确定值的类型,第二个:指定key的名字,第三个:传值
上面的意思是:为LOG_DEBUG = true
那这个值怎么读取呢?在Groovy中,直接由BuildConfig类点出key名来取值,如下:

if(BuildConfig.LOG_DEBUG){
//Debug,打印日志
Logger.init("AppPlusLog").setLogLevel(LogLevel.FULL);
}else{
//release,关闭日志
Logger.init("AppPlusLog").setLogLevel(LogLevel.None);
}

同样的,网络切换也可以这样设置

buildConfigField "String", "SERVER_HOST", "\"200.200.200.50/\""

//取值
String host = BuildConfig.SERVER_HOST;
//然后再把这个host替换掉默认的那个
---------------------

Gradle 中 buildConfigField的巧妙应用的更多相关文章

  1. gradle中使用嵌入式(embedded) tomcat, debug 启动

    在gradle项目中使用embedded tomcat. 最开始部署项目需要手动将web项目打成war包,然后手动上传到tomcat的webapp下,然后启动tomcat来部署项目.这种手动工作通常还 ...

  2. 在Gradle中使用jaxb的xjc插件

    jaxb,全称为Java Architecture for Xml Binding,是一种将java对象与xml建立起映射的技术.其主要提供两个功能,一是将java对象映射为xml,二是将xml映射为 ...

  3. Gradle中的buildScript代码块

    在编写Gradle脚本的时候,在build.gradle文件中经常看到这样的代码: build.gradle 1 2 3 4 5 6 7 8 9 buildScript { repositories ...

  4. Gradle中使用idea插件的一些实践

    如果你的项目使用了Gradle作为构建工具,那么你一定要使用Gradle来自动生成IDE的项目文件,无需再手动的将源代码导入到你的IDE中去了. 如果你使用的是eclipse,可以在build.gra ...

  5. [转] Gradle中的buildScript代码块

    PS: 在build script中的task apply plugin: 'spring-boot' 需要 classpath("org.springframework.boot:spri ...

  6. gradle中使用cobertura做代码覆盖(转)

    gradle很好用,但是默认是没有代码覆盖功能的,只好自己写.曾经在网上找到过别人的一段脚本,虽然也能用,但是有一些不爽的地方,一个原因是它不支持对层级工程中全部代码的覆盖,另一个原因是它用替换bui ...

  7. Gradle 1.12 翻译——第十七章. 从 Gradle 中调用 Ant

    有关其他已翻译的章节请关注Github上的项目:https://github.com/msdx/gradledoc/tree/1.12,或访问:http://gradledoc.qiniudn.com ...

  8. Gradle中的闭包

    Gradle是基于Groovy的DSL基础上的构建工具,Gradle中的闭包,其原型上实际上即Groovy中闭包.而在表现形式上,其实,Gradle更多的是以约定和基于约定基础上的配置去展现.但本质上 ...

  9. 在 Gradle 中使用 MyBatis Generator

    在 Intellij IDEA 中结合 Gradle 使用 MyBatis Generator 逆向生成代码 Info: JDK 1.8 Gradle 2.14 Intellij IDEA 2016. ...

随机推荐

  1. BZOJ1084 [SCOI2005]最大子矩阵 动态规划

    欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - BZOJ1084 题意概括 这里有一个n*m的矩阵,请你选出其中k个子矩阵,使得这个k个子矩阵分值之和最大.注 ...

  2. 针对mysql delete删除表数据后占用空间不变小的问题

    开发环境 Yii1版本 MySQL PHP5.6.27 前言 物流规则匹配日志表记录订单匹配规则相关日志信息,方便管理员维护和查阅不匹配的订单,四个月时间,该日志表数据就有174G,当前,这么大的数据 ...

  3. Unicode字符编码表(转)

    Unicode字符编码表     版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/zhenyu5211314/article/details/5153 ...

  4. Linux学习之文件属性chattr权限与sudo权限(十二)

    Linux学习之文件属性chattr权限与sudo权限 文件属性chattr Linux文件的隐藏属性在保护系统文件的安全性上非常重要,是防止误操作的,对root用户也同样有效.chattr命令只能在 ...

  5. Linux系统 vi/vim文本编辑器

    Linux系统 vi/vim文本编辑器 (一)Vim/Vi简介 (二)Vim/Vi工作模式 (三)Vim/Vi基本使用 (四)Vim/Vi应用技巧 (一)Vim/Vi简介 Vim/Vi是一个功能强大的 ...

  6. 从字符集发展史看Unicode和UTF-8的区别

    从字符集发展史看Unicode和UTF-8的区别 版权声明 本文并非本人原创,其内容来源于网络,本文根据其演绎而来,具体出出已经无法考证,在这里只好给出我所参考的连接. 知乎 https://www. ...

  7. BZOJ.4892.[TJOI2017]DNA(后缀自动机/后缀数组)

    题目链接 \(Description\) 给出两个串\(S,T\),求\(T\)在\(S\)中出现了多少次.出现是指.可以有\(3\)次(\(3\)个字符)不匹配(修改使其匹配). \(Solutio ...

  8. Python3.x使用PyMysql连接MySQL数据库

    Python3.x使用PyMysql连接MySQL数据库 由于Python3.x不向前兼容,导致Python2.x中的很多库在Python3.x中无法使用,例如Mysqldb,我前几天写了一篇博客Py ...

  9. [BZOJ5427]最长上升子序列/[BZOJ4282]慎二的随机数列

    [BZOJ5427]最长上升子序列/[BZOJ4282]慎二的随机数列 题目大意: 给你一个长度为\(n(n\le10^5)\)的整数序列,其中有一些数已经模糊不清了,现在请你任意确定这些整数的值,使 ...

  10. treap(树堆)

    一棵treap是一棵修改了结点顺序的二叉查找树,如图,显示一个例子,通常树内的每个结点x都有一个关键字值key[x],另外,还要为结点分配priority[x],它是一个独立选取的随机数. 假设所有的 ...