将 API 密钥保存在 gradle.properties 中 [英] Saving the API Key in gradle.properties
问题描述
我是 android 新手,正在从事一个项目,我看到我获得的 API 密钥保存在 gradle.properties
中为:
I am new to android and working on a project where I see that the API key that I got is saved in gradle.properties
as :
MyOpenWeatherMapApiKey="1c3ae96f93a0094e8a7chsjdgfid04aed3f10"
然后在 build.gradle(module:app)
我添加以下几行:
And then in build.gradle(module:app)
I am adding the following lines :
buildTypes.each {
it.buildConfigField 'String', 'OPEN_WEATHER_MAP_API_KEY', MyOpenWeatherMapApiKey
}
因此,在我的主程序中,我使用此 api 访问数据,其 URL 由这段代码获取:
So, in my main program I am accessing the data using this api whose URL is got by this piece of code :
final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
final String APPID_PARAM = "APPID";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY)
.build();
URL url = new URL(builtUri.toString());
所以,我的问题是,为什么要承担所有更改的所有压力以将 appid 存储在 gradle 部分.不能只在主程序中直接访问吗?
So, my question is that why taking all the tension of doing changes to store the appid in the gradle part. Can't we access directly in the main program only ?
我的问题的第二部分是 gradle 部分实际发生了什么,尤其是 buildTypes.each{}
块?
And the second part of my question is what is actually happening in the gradle part especially with the buildTypes.each{}
block ?
推荐答案
- 这种间接方式的想法是允许您将 API 密钥存储在未上传到版本控制的文件中:
gradle.properties
是本地文件,不应存储在版本控制下, 而BuildConfig
是一个生成的类,所以它只会在构建时创建.将 API 密钥作为普通字符串存储在某处肯定更容易,但您必须将其提交到存储库. - 在构建期间,Gradle 会生成
BuildConfig
文件来存储一些与构建相关的常量.您可以使用buildConfigField
命令来指示 Gradle 将自定义字段添加到BuildConfig
中.项目构建完成后,您可以在源代码中引用这些常量.
- The idea of this indirection is to allow you to store API key in files that are not uploaded to the version control:
gradle.properties
is a local file and should not be stored under the version control, andBuildConfig
is a generated class, so it will only be created at build time. It's definitely easier to store the API key somewhere as a plain String, but then you'll have to commit it to the repo. - During build time, Gradle will generate the
BuildConfig
file to store some build-related constants. You can usebuildConfigField
command to instruct Gradle to add custom fields intoBuildConfig
. After the project is built, you can reference these constants inside your source code.
这篇关于将 API 密钥保存在 gradle.properties 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!