在Android开发中我们也许需要一些全局的配置信息,我们可以将它配置在gradle.properties文件中,比如某个电影网站提供的api_key="你的API_key"
1.在gradle.properties文件中添加如下:
tmdb_api_key=ADD_YOUR_API_KEY_HERE
2.在app的gradle文件中如下位置:
在gradle文件开头位置添加:
apply plugin: 'com.android.application'
def getProperty(String filename, String propName) {
def propsFile = rootProject.file(filename)
if (propsFile.exists()) {
def props = new Properties()
props.load(new FileInputStream(propsFile))
if (props[propName] != null) {
return props[propName]
} else {
print("No such property " + propName + " in file " + filename)
}
} else {
print(filename + " does not exist!")
}
}
....
defaultConfig {
applicationId "com.esoxjem.movieguide"
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"
buildConfigField "String", "TMDB_API_KEY", "\"${getProperty("gradle.properties", "tmdb_api_key")}\""
buildConfigField "String", "TMDB_BASE_URL", "\"https://api.themoviedb.org/\""
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
3.点击Make Project按钮
4.在项目中按照如下方式获取即可:
MainActivity.class:
String apiKey = BuildConfig.TMDB_API_KEY