问题描述
我想在 local.properties
中添加自定义字段,例如
I want to add custom fields in local.properties
like
debug.username=test123
debug.password=abcd1234
可以在assets文件夹中添加.properties
文件并轻松阅读.
can add .properties
files in assets folder and read that easily.
Resources resources = context.getResources();
AssetManager assetManager = resources.getAssets();
Properties properties = null;
InputStream inputStream = assetManager.open(fileName);
properties = new Properties();
properties.load(inputStream);
但是不想这样做.因为我希望我们的每个团队成员都使用 local.properties
来指定自定义属性.这不是版本控制系统的一部分.
But don't want to do this.As i want every team member of our to use local.properties
to specify there custom attribute. which is not the part of version control system.
那么如何在运行时读取local.properties
放在java文件中基于gradle的android项目的根文件夹?
So how to read local.properties
placed in the root folder of gradle based android project in java files at runtime?
推荐答案
我知道这是一个老问题,但我最近遇到了同样的事情,我想我会分享我的解决方案:
I know that this is an old question but I recently encountered the same thing and I thought I'd share my solution:
- 在您的 local.properties 文件中设置该值.
- 读取 Gradle 构建脚本中的值并将其设置为
BuildConfig
常量. - 访问 Java 代码中的
BuildConfig
常量.
- Set the value in your local.properties file.
- Read the value in your Gradle build script and set it to a
BuildConfig
constant. - Access the
BuildConfig
constant in your Java code.
local.properties
username=myUsername
build.gradle:
def getUsername() {
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
return properties.getProperty("username");
}
android {
defaultConfig {
buildConfigField "String", "USERNAME", "\""+getUsername()+"\""
}
}
示例 Java 类:
package your.package.name;
class MyClass {
String getUsername() {
return BuildConfig.USERNAME; // Will return "myUsername"
}
}
这篇关于如何在java文件中读取local.properties android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!