无法获取未知属性“ localProperties”

时间:2019-12-08 23:58:00

标签: android gradle

我想读取在 build.gradle 中的 local.properties 中定义的属性(如here所述) 因此,在根 build.gradle 文件中,我具有以下内容:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

def localProperties = new Properties()
if (project.rootProject.file('local.properties').canRead()) {
    localProperties.load(project.rootProject.file("local.properties").newDataInputStream())
}

buildscript {

    ext {
        ...
    }

    repositories {
        google()
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
    dependencies {
        classpath "com.android.tools.build:gradle:$gradleVersion"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"


        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

在模块的 build.gradle 文件中,我具有以下内容:

android {
    ...
    defaultConfig {
        ...
        buildConfigField "String", "TOKEN", localProperties['token']
    }
}

但是同步后,出现以下错误:

  

无法获得以下未知属性“ localProperties”   类型的DefaultConfig_Decorated {name = main,...}   com.android.build.gradle.internal.dsl.DefaultConfig。

我在哪里错了?如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

我遇到了一些问题。变量localProperties不是内置的,而是由您自己定义的。您可以添加

Properties localProperties = new Properties()
    File file = project.rootProject.file('local.properties')
    if (file.exists()) {
        localProperties.load(file.newDataInputStream())
    }

在defaultConfig块中进行build.gradle。

答案 1 :(得分:0)

在“android”部分下的build.gradle中,您需要添加

android {
def localProperties = new Properties()
localProperties.load(new FileInputStream(rootProject.file("local.properties")))
...}