我有 gradle 项目,其 build.gradle 的简化 android 部分如下所示:
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
minSdkVersion 15
targetSdkVersion 22
versionCode 1
versionName "1.0"
def mapPlacesApiKeys = [dev_1: [api_key: 'key_1', sender_id: 'sender_id_1'], dev_9: [api_key: 'key_2', sender_id: 'sender_id_2'],prod_1: [api_key: 'key_3', sender_id: 'sender_id_3']]
if (project.hasProperty('env')) {
if (mapPlacesApiKeys.get(env) == null) {
def keyset = mapPlacesApiKeys.keySet()
throw new StopExecutionException("Value '$env' is not a valid environment value. Valid environments: $keyset. You can set an environment by passing the -Penv=<env> parameter to your gradle build.")
}
}
buildConfigField "String", "SENDER_ID", "\"${mapPlacesApiKeys.get(env).get('sender_id')}\""
manifestPlaceholders = [maps_places_api_key: mapPlacesApiKeys.get(env).get('api_key')]
}
}
当我从命令行运行它时,我使用环境参数运行它,例如-Penv=dev_1。正如您在脚本中看到的那样,这会做两件事: a) 将 androidmanifest 中的值“maps_places_api_key”替换为指定环境的实际 key b) 在 BuildConfig java 类中添加一个带有 SENDER_ID 的字符串。
这在命令行中运行良好。我的问题是,在 intellij(或 android studio,应该相同)中,当我导入 gradle 项目时出现以下错误:
-Penv is missing. You can set an environment by passing the -Penv=<env> parameter to your gradle build.
这是我要声明的异常(exception)。所以我的问题是如何构建此代码,以便 IDE 在加载项目时不会尝试运行它。
请注意,我不想用任何类型的 flavors 或 buildTypes 替换“env”参数,因为大约有 15 种不同的环境,它会变得一团糟,但如果你想到另一个建议免费分享。
最佳答案
android{
defaultConfig {
applicationId 'com.xx'
minSdkVersion 14
}
productFlavors {
def path="./channel.txt"
file(path).eachLine { line->
def words = line.split(':')
def name = words[0]
def sender_id = words[1]
def api_key = words[2]
"$name" {
buildConfigField "String", "SENDER_ID", sender_id
manifestPlaceholders = [maps_places_api_key: api_key]
}
}
}
}
关于android - Intellij - 需要参数的android项目的gradle刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34693588/