BuildConfig
从sdk tools 17开始,构建工具会自动生成BuildeConfig类,默认的长这个样子
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.example.ty.testapplication";
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";
}
这个类我们可以用来自动在Release版本关闭某些功能。比如日志,只需要判断DEBUG变量即可。我们可以通过gradle来为这个类增加成员变量。
android {
buildTypes {
debug {
buildConfigField "String", "API_URL",
"\"http://test.example.com/api\""
buildConfigField "boolean", "LOG_HTTP_CALLS", "true"
}
release {
buildConfigField "String", "API_URL",
"\"http://example.com/api\""
buildConfigField "boolean", "LOG_HTTP_CALLS", "false"
}
}
}
这里我们增加了一个Field,API_URL值就是下面那个地址,注意字符串两个转义的引号是不能少的。
这里我们就生成了新的BuildConfig
public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.example.ty.testapplication";
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 API_URL = "http://test.example.com/api";
public static final boolean LOG_HTTP_CALLS = true;
}
resValue
gradle同样可以用来生成资源文件,比如生成一个字符串资源。
buildTypes {
debug {
resValue "string", "app_name", "Example DEBUG"
}
release {
resValue "string", "app_name", "Example"
}
}
这里生成的字符串在资源文件里无法找到,但是代码里可以引用。比如debug和release的app名字,可以通过这种方式直接修改,是不是特别方便。