Java中使用Gradle中声明的变量

问题描述

是否可以在Gradle中声明一个可用于Java的变量?即在build.gradle中声明一些vars,然后在构建时得到这些变量。就像在C/C++中的pre-processor宏…

参考:https://stackoverflow.com/questions/17197636/is-it-possible-to-declare-a-variable-in-gradle-usable-in-java

最佳解决方案

生成Java常量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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资源

1
2
3
4
5
6
7
8
9
10
android {
buildTypes {
debug {
resValue "string", "app_name", "My App Name Debug"
}
release {
resValue "string", "app_name", "My App Name Release"
}
}
}

可以使用@string/app_nameR.string.app_name以常规方式访问

次佳解决方案

Store api keys with help of gradle and the gradle.properties file (Java + XML)

  • gradle.properties
1
AppKey="XXXX-XXXX"
  • build.gradle
1
2
3
4
5
6
7
buildTypes {
//...
buildTypes.each {
it.buildConfigField 'String', 'APP_KEY_1', AppKey
it.resValue 'string', 'APP_KEY_2', AppKey
}
}
  • Usage in java code
1
2
3
Log.d("UserActivity", "onCreate, APP_KEY: " + getString(R.string.APP_KEY_2));

BuildConfig.APP_KEY_1
  • Usage in xml code
1
<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设置在运行时传递的系统属性:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
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);
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :