问题描述
是否可以在Gradle中声明一个可用于Java的变量?即在build.gradle中声明一些vars,然后在构建时得到这些变量。就像在C/C++中的pre-processor宏…
最佳解决方案
生成Java常量
android {
buildTypes {
debug {
buildConfigField "int", "FOO", "42"
buildConfigField "String", "FOO_STRING", "\"foo\""
buildConfigField "boolean", "LOG", "true"
}
release {
buildConfigField "int", "FOO", "52"
buildConfigField "String", "FOO_STRING", "\"bar\""
buildConfigField "boolean", "LOG", "false"
}
}
}
可以使用BuildConfig.FOO访问
生成Android资源
android {
buildTypes {
debug {
resValue "string", "app_name", "My App Name Debug"
}
release {
resValue "string", "app_name", "My App Name Release"
}
}
}
可以使用@string/app_name或R.string.app_name以常规方式访问
次佳解决方案
Store api keys with help of gradle and the gradle.properties file (Java + XML)
- gradle.properties
AppKey="XXXX-XXXX"
- build.gradle
buildTypes {
//...
buildTypes.each {
it.buildConfigField 'String', 'APP_KEY_1', AppKey
it.resValue 'string', 'APP_KEY_2', AppKey
}
}
- Usage in java code
Log.d("UserActivity", "onCreate, APP_KEY: " + getString(R.string.APP_KEY_2));
BuildConfig.APP_KEY_1
- Usage in xml code
<data android:scheme="@string/APP_KEY_2" />
Link to an example of Api App Key usage in an Android application
Using String Constants Generated by Gradle Build Configurations
第三种解决方案
使用系统属性,在build.gradle中设置,从Java应用程序读取
在build.gradle中使用test任务,使用测试任务方法systemProperty设置在运行时传递的系统属性:
apply plugin: 'java'
group = 'example'
version = '0.0.1-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testCompile 'junit:junit:4.8.2'
compile 'ch.qos.logback:logback-classic:1.1.2'
}
test {
logger.info '==test=='
systemProperty 'MY-VAR1', 'VALUE-TEST'
}
Java中获取系统属性MY-VAR1,在runtime被设置为VALUE-TEST:
package example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorld {
static final Logger log = LoggerFactory.getLogger(HelloWorld.class);
public static void main(String args[]) {
log.info("entering main...");
final String val = System.getProperty("MY-VAR1", "UNSET (MAIN)");
System.out.println("(main.out) hello, world: " + val);
log.info("main.log) MY-VAR1=" + val);
}
}