在进行项目开发或维护时,经常会遇到调试和发布所用到的参数值不一致的情况
例如,服务器会分测试和正式,为了能方便地更改(自动更换)服务器地址,buildConfigField就派上用场了
以前都是手动更改的,极易出错T_T
buildConfigField语法如下
buildConfigField "TypeName", "FieldName", "FieldValue"
示例
build.gradle (Module: app)
apply plugin: 'com.android.application' android {
compileSdkVersion 28
defaultConfig {
applicationId "com.bu_ish.debug_release_test"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
buildConfigField "String", "TextToShow", "\"当前处于发布模式\""
}
debug {
buildConfigField "String", "TextToShow", "\"当前处于调试模式\""
}
}
} dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Gradle会自动生成BuildConfig.java
BuildConfig中包含了字段TextToShow
生成的Debug版BuildConfig如下
/**
* Automatically generated file. DO NOT MODIFY
*/
package com.bu_ish.debug_release_test; public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.bu_ish.debug_release_test";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0";
// Fields from build type: debug
public static final String TextToShow = "当前处于调试模式";
}
在使用BuildConfig.TextToShow时,Gradle就帮我们自动地完成了调试值"当前处于调试模式"和发布值"当前处于发布模式"的切换