ot;1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
myType {
initWith debug //完全复制 debug 的所有属性‘
minifyEnabled true //自定义打开混淆
}
}
}
applicationIdSuffix 、versionNameSuffix :添加后缀
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.wifi.analytics"
minSdkVersion 9
targetSdkVersion 25
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
applicationIdSuffix "zhao" //applicationId 追加后缀名 zhao
versionNameSuffix "debug" //versionName 追加后缀名 debug1.0
}
}
效果图,如下:
buildConfigField: 自定义属性
在 build.gradle 文件中定义 buildConfigField 属性
android {
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField "String", "API_ENV", "\"http://yiba.com\"" //自定义String属性
}
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField "String", "API_ENV", "\"http://yiba.com\"" //自定义String属性
}
}
}
然后点击同步按钮,然后就可以在 build 目录看到 debug 和 release 信息。
debug 环境下的 BuildConfig 如下:
release 环境下的 BuildConfig 如下:
当然我们也可以在代码中获取自定义的值:
//获取变量值
String API = BuildConfig.API_ENV ;
上面演示了自定义 String 变量,也可以 自定义 int 、boolean
android {
buildTypes {
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
buildConfigField "String", "API_ENV", "\"http://www.baidu.com\"" //自定义 String 值
buildConfigField "Boolean", "openLog", "true" //自定义 boolean 值
buildConfigField "int", "age", "10" //自定义 int 值
}
}
}
Gradle 实现差异化构建
情景1
LeakCanary 是 square 公司出品的一个检测内存泄漏的开源库。
GitHub : https://github.com/square/leakcanary
我们一般这样集成
dependencies {
compile 'com.squareup.leakcanary:leakcanary-android:1.5.2'
}
然后我们在 Application 类中初始化:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
LeakCanary.install(this);
}
}
但是这样集成有一个弊端,就是 debug 和 release 包都会把 LeakCanary 的源码打进去,如果我们在 release 包中不把 LeakCanary 源码打进去,怎么办? 还好 LeakCanary 给我们提供了一个方法,方法如下:
dependencies {
//打 debug 包
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'
//打 release 包
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
}
leakcanary-android-no-op 是一个空壳,里面有2个空类,所以就可以避免把 LeakCanary 源码打进 release 包。但是这种方式有个缺陷,如果一些开源库没有提供 releaseCompile 库,那我们改怎么办了?下面的情景2 就会讲到解决方案。
情景2
Stetho 是 Faceboo k开源的Andorid调试工具。当你的应用集成Stetho时,开发者可以访问Chrome,在Chrome Developer Tools中查看应用布局,网络请求,sqlite,preference 等等。
官网:http://facebook.github.io/stetho/
从官网可以看到 stetho 没有提供 releaseCompile 包 , 情景1 的方案就不能用了。