我使用的一个选项是将API密钥存储在计算机/钥匙串中,而不是直接放在云备份的项目代码中(名为gradle-credentials-plugin)。我希望能以类似的方式管理Google Maps密钥,但它们用于不同的文件(在Android Studio中使用Gradle管理Google Maps API密钥)。
如果有人可以向我介绍一个简单(或复杂但可靠)的选项,我将不胜感激!
如果有人可以向我介绍一个简单(或复杂但可靠)的选项,我将不胜感激!
您可以使用 manifestPlaceholders 将字符串从您的 build.gradle
注入。
local.properties
这样的文件中。google.maps_api_key=SECRET_KEY
.gitignore
忽略此文件:local.properties
AndroidManifest.xml
。使用withInputStream()
确保InputStream
自动关闭。android{
defaultConfig {
// Load credentials.
def properties = new Properties()
file("../local.properties").withInputStream { properties.load(it) }
// Share the key with your `AndroidManifest.xml`
manifestPlaceholders = [ googleMapsApiKey:"${properties.getProperty('google.maps_api_key')}"]
AndroidManifest.xml
中加载API密钥:<application>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="${googleMapsApiKey}" />
local.properties
从 git 中排除,因为通常不希望在存储库中存储敏感信息(这里是 Google Map Key)。即使您的存储库是私有的,您(或您的分支)可能会在某个时候将其设置为公共,然后其他人可以从 Git 历史记录中检索密钥。但这不是在此评论部分讨论的主题 :)。 - hb0api.keys
,并将以下内容写入该文件:debugMapsApiKey=xxxxXXXxxxx
releaseMapsApiKey=xxxYYYxxx
将它放在你的根项目文件夹中。
在你的build.gradle
文件中,可以像这样读取该文件:
def apiKeysFile = rootProject.file("api.keys")
def apiKeysFile = new Properties()
apiKeysFile.load(new FileInputStream(apiKeysFile))
[...]
debug {
buildConfigField "String", MAPS_KEY, apiKeysFile['debugMapsApiKey']
}
release {
buildConfigField "String", MAPS_KEY, apiKeysFile['releaaseMapsApiKey']
}
你可以通过以下代码访问它:
BuildConfig.MAPS_KEY
。如果你在调试中构建,值为"xxxxXXxxxx"
,而在发布中则为"xxxxYYxxxx"
。
如果你想在XML中访问它,可以使用resValue
创建一个字符串资源。
debug {
resValue "string", MAPS_KEY, apiKeysFile['debugMapsApiKey']
}
release {
resValue "string", MAPS_KEY, apiKeysFile['releaseMapsApiKey']
}
通过这种方式,您也可以使用代码获取它
getString(R.string.MAPS_KEY)
google_maps_api.xml
<resources>
<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">GoogleMapsApiKey</string>
</resources>
清单
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/GoogleMapsApiKey"/>
gradle
resValue "string", "GoogleMapsApiKey", mapskey
gradle.properties
mapskey="AIza...8w" // key here
Shadowsheep的解决方案可行,但不是我想要做的。
最终我做了以下步骤:
首先,我错误地认为必须使用密钥来填充google-maps-api.xml,而实际上在清单中设置密钥就足够了。
其次,我在清单中添加了一行<meta-data android:name="com.google.android.geo.API_KEY" android:value"@string/GoogleMapsApiKey">
。
第三,我通过我选择的工具(etiennestuder的gradle-credentials-plugin)设置了mapsKey。
最后,我在应用程序模块的build.gradle buildTypes
部分中添加了以下两行:
def mapsKey = credentials.GOOGLE_MAPS_API_KEY ?: "Key Missing"
it.resValue "string", "GoogleMapsApiKey", mapsKey
credentials.whateverYouCallYourMapsApiKey
来填充resValue
。 - CommonsWareapi.keys
的文件,其中包含你的密钥,并且你忽略它,那么这将是一个很好的解决方案,因此它不会被版本控制,只存在于你的电脑上。这样,在发布版本中获取生产密钥,在调试版本中获取开发密钥,这将是一个不错的选择。 - shadowsheep