繁体   English   中英

如何声明一个对所有模块的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"))

一个更像常规的语法是你更喜欢的:

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

这样,您可以在所有模块中复制代码,但至少您的问题已解决。

第二个选项是使用ExtraPropertiesExtension我个人从未使用它但是根据Android gradle构建问题的响应:如何设置全局变量它似乎做你想要的。

UPDATE

如果要使用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

module的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文档建议使用rootProject.ext 在顶级build.gradle中(取自配置项目范围的属性 ):

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}"
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM