有两种方法可以做到:
1/ 按string
你想要的资源
添加一个名为secret_keys.xml
或任何名称的资源文件以将其与其他资源文件分开。translatable="false"
将您的密钥、api 端点作为普通字符串资源放在这里,如果您不想弄乱本地化,请记住添加。
将该文件放在app/debug/res/values/
. debug
如果不存在,则创建一个新文件夹。staging
对or执行相同release
操作,Android 将自动使用与构建类型同名的文件夹。
2/ 按properties
文件
创建 3 个 .properties 文件并将密钥放入其中:

HOST="http://api.blablabla.com"
CLIENT_ID="hahaha"
CLIENT_SECRET="hehehe"
将其绑定到BuildConfig
应用程序中的变量,build.gradle
对其他构建类型执行相同操作:
def getPropertiesFile = { path ->
Properties properties = new Properties()
properties.load(new FileInputStream(file(path)))
return properties
}
android {
...
buildTypes {
debug {
...
getPropertiesFile('./config/development.properties').each { p ->
buildConfigField 'String', p.key, p.value
}
}
...
}
}
在您的应用程序中,只需调用BuildConfig.HOST
即可获取您想要的字符串
更新
忽略这些配置文件.gitignore
:
app/config
secret_keys.xml