什么是gradle.properties用于? (并使用外部变量)

时间:2016-12-07 20:37:49

标签: android android-gradle gradle.properties

我一直在开发Android应用程序,但后来意识到我还不知道gradle.properties文件的用途。

我已经通过the Gradle documentation阅读了一些内容,这解释了您可以添加用于指定Java主目录或内存设置的配置。还有什么可以用于吗?

我这样的时候的主要参考通常是Google I / O开源应用,看看its gradle.properties file,我可以看到它的一个用途是存储依赖版本变量,所以版本代码例如,对于Android支持库依赖项,不需要使用库的新版本进行更新,只需更新一个变量:

...

// Android support libraries.
compile "com.android.support:appcompat-v7:${android_support_lib_version}"
compile "com.android.support:cardview-v7:${android_support_lib_version}"
compile "com.android.support:design:${android_support_lib_version}"
compile "com.android.support:support-v13:${android_support_lib_version}"
compile "com.android.support:recyclerview-v7:${android_support_lib_version}"
compile "com.android.support:preference-v7:${android_support_lib_version}"

...

Google Play服务使用了同样的想法。

然而,在我自己的一个Android项目中,我一直在做类似的事情 - 我将我的版本变量放在根build.gradle文件中,如下所示:

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

buildscript {
    ext.kotlin_version = '1.0.5-2'

    repositories {
        ...
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }

    ...

然后我一直在我的模块build.gradle中使用它,如此:

dependencies {

    ...

    // Kotlin standard library
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

    ...
}

所以我猜我有几个问题:

  1. gradle.properties文件还用于什么?

  2. gradle.properties中使用外部变量(如在iosched中)和在根build.gradle中的外部变量之间有什么区别(正如我一直在做的那样)?

    • 哪个是首选方法,如果有的话?
    • 以某种特定的方式做优点/缺点吗?

1 个答案:

答案 0 :(得分:4)

我正在使用它(在app/build.gradle内):

signingConfigs {
    release {
        keyAlias RELEASE_KEY_ALIAS
        keyPassword RELEASE_KEY_PASSWORD
        storeFile file(RELEASE_STORE_FILE)
        storePassword RELEASE_STORE_PASSWORD
    }
}

productFlavors {
    ....
    prod {
        applicationIdSuffix ".prod"
        buildConfigField "String", "BASE_URL", BASE_URL_PROD
    }
    ....
}

buildTypes.each {
    it.buildConfigField "Double", "CONTACT_MAP_LATITUDE", CONTACT_MAP_LATITUDE
    it.buildConfigField "Double", "CONTACT_MAP_LONGITUDE", CONTACT_MAP_LONGITUDE
    it.resValue "string", "google_maps_api_key", GOOGLE_MAPS_API_KEY
}

RELEASE_KEY_ALIASRELEASE_KEY_PASSWORDRELEASE_STORE_FILERELEASE_STORE_PASSWORDBASE_URL_PRODCONTACT_MAP_LATITUDECONTACT_MAP_LONGITUDEGOOGLE_MAPS_API_KEY所有都在gradle.properties内,并且该文件不会被推送到git

示例:

gradle.properties:BASE_URL_PROD = "http://something.com/api/"

build.gradle:buildConfigField "String", "BASE_URL", BASE_URL_PROD

java文件:BuildConfig.BASE_URL

编辑:此外,您可以在这里找到服务器应用程序的示例(Spring):https://melorriaga.wordpress.com/2016/08/06/gradle-dont-store-api-keys-and-db-information-in-versioned-files/

相关问题