我要保护我的API密钥是因为我想上传一个公共存储库,因此在尝试时将其尝试并将密钥添加到gradle.properties
文件中
buildTypes {
debug {
buildConfigField 'String', "FIRST_APIKEY", "\"FIRST_APIKEY\""
buildConfigField 'String', "SECOND_APIKEY", "\"SECOND_APIKEY\""
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
FIRST_APIKEY = "apikey"
SECOND_APIKEY = "apikey"
它说apikey是当前的字母数字apikey
当我将其实现到类中以获取该apikey时,它不会返回apikey
例如,在这里,我试图从该apikey解析数据,但我什么也没得到,因为无法访问它
service.getData(BuildConfig.FIRST_APIKEY)....
使用调试器生成BuildConfig.FIRST_APIKEY的结果如下
结果= FIRST_APIKEY
代替FIRST_APIKEY,它应该实现我先前在gradle.properties
文件中配置的apikey
感谢任何提示
答案 0 :(得分:1)
您不应分配静态字符串,而应分配变量:
buildConfigField("String", "FIRST_APIKEY", "\"${firstApiKey}\"")
resValue("string", "first_api_key", "${firstApiKey}")
,除非加载它们,否则它可能不关心任何.properties
;例如:
def apikeys = new Properties()
apikeys.load(new FileInputStream(rootProject.file('apikeys.properties')))
project.ext.set('firstApiKey', apikeys['firstApiKey'])
答案 1 :(得分:1)
首先,在gradle的配置阶段将属性加载到Properties
对象中:
apply plugin: 'com.android.application'
Properties localProperties = new Properties()
localProperties.load(project.rootProject.file('local.properties').newDataInputStream())
然后您可以找到buildConfigField
的财产:
buildConfigField 'String', "FIRST_APIKEY", localProperties.getProperty('FIRST_APIKEY')
buildConfigField 'String', "SECOND_APIKEY", localProperties.getProperty('SECOND_APIKEY')
如果您的属性如下所示:
FIRST_APIKEY=apikey
SECOND_APIKEY=apikey
然后,您需要将localProperties.getProperty('FIRST_APIKEY')
替换为"\"${props.getProperty('FIRST_APIKEY')}\""
。