如何声明一个对所有模块的 build.gradle 文件可见的常量?

How to declare a constant that is visible to all modules' build.gradle file?

我有一个包含多个模块的项目 - 库和应用程序。每次Android的新版本出来,我都需要升级所有模块的targetSdk、compileSdk、buildToolsVersion等。常量可以帮助完成这项繁琐的工作!

如何定义对所有模块 build.gradle 可见的项目级常量?

我选择做类似事情的方法是创建一个属性文件,然后只为我所有的全局变量读取它。您可以使用 java 语法执行此操作:

Properties props = new Properties()
props.load(new FileInputStream("/path/file.properties"))

更 groovy 的语法是您喜欢的语法:

Properties props = new Properties()
File propsFile = new File('/usr/local/etc/test.properties')
props.load(propsFile.newDataInputStream())

这样,您可能会在所有模块中重复代码,但至少您的问题得到了解决。

第二种选择是使用 ExtraPropertiesExtension I've personally never used it but according to the response to the question Android gradle build: how to set global variables 它似乎可以满足您的需求。

更新

如果要使用 ExtraPropertiesExtension 执行此操作,请在您的 <project base>/build.gradle 中添加:

allprojects {
    repositories {
        jcenter()
    }
    //THIS IS WHAT YOU ARE ADDING
    project.ext {
        myprop = "HELLO WORLD";
        myversion = 5
    }
}

同步后,在每个模块的 build.gradle 文件中,您可以像这样使用:

System.out.println(project.ext.myprop + " " + project.ext.myversion)

对于 Android Studio 用户

您可以在文件 "gradle.properties" 中定义常量并在模块的 gradle 文件中使用它们。

gradle.properties

ANDROID_BUILD_MIN_SDK_VERSION = 16
ANDROID_BUILD_TARGET_SDK_VERSION= 20
ANDROID_BUILD_TOOLS_VERSION=20.0.0
ANDROID_BUILD_SDK_VERSION=20
ANDROID_BUILD_COMPILE_SDK_VERSION=21

模块的build.gradle文件

android {
    compileSdkVersion project.ANDROID_BUILD_COMPILE_SDK_VERSION=21
    buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION

    defaultConfig {
        applicationId "com.abc.def"
        minSdkVersion project.ANDROID_BUILD_MIN_SDK_VERSION
        targetSdkVersion project.ANDROID_BUILD_TARGET_SDK_VERSION
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

对于 Android 个项目,Android docs 建议使用 rootProject.ext。 在你的顶级build.gradle(取自Configure project-wide properties):

buildscript {...}
allprojects {...}

// This block encapsulates custom properties and makes them available to all
// modules in the project.
ext {
    // The following are only a few examples of the types of properties you can define.
    compileSdkVersion = 26
    // You can also use this to specify versions for dependencies. Having consistent
    // versions between modules can avoid behavior conflicts.
    supportLibVersion = "27.1.1"
    ...
}
...

然后,在您的子模块中,您可以像这样引用这些变量:

android {
  // Use the following syntax to access properties you define at the project level:
  // rootProject.ext.property_name
  compileSdkVersion rootProject.ext.compileSdkVersion
  ...
}
...
dependencies {
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    ...
}