如何获取Android project下 build.gradle、gradle.properties、local.properties文件中定义的属性或变量

1、读取project下 build.gradle

属性:

ext {
    compileSdk = 28
    minSdk = 17
    targetSdk = 28
    support = "28.0.0"
    buildTools = "28.0.0"
    supportLibraryVersion = "28.0.0"
    versionCode = 4
    versionName = "1.0.4"

    cfgs = [
            utilcodeVersion: "1.23.0",
            eventbusVersion: "3.0.0",
            glideVersion: "3.7.0",
            retrofitVersion: "2.4.0",
            rxandroidVersion: "1.1.0",
            rxjavaVersion: "1.1.0",
            okhttpVersion: "3.5.0",
            loggingInterceptorVersion: "3.0.0",
            autosizeVersion: "1.1.2",
            baseRecyclerViewAdapterHelperVersion: "2.9.30",
            lottieVersion: "2.1.0",
            fastjsonVersion: "1.2.47",
            qmuiVersion: "1.1.3",
            bottomNavigationBarVersion: "2.1.0",
            recyclerViewVersion: "28.0.0",
            zhihuMatisse:"0.5.2-beta2"
    ]
}

读取:

defaultConfig {
    applicationId "com.star.commodity.release"
    minSdkVersion rootProject.ext.minSdk
    targetSdkVersion rootProject.ext.targetSdk
    versionCode rootProject.ext.versionCode
    versionName rootProject.ext.versionName
    multiDexEnabled true
}
implementation "com.android.support:appcompat-v7:${supportLibraryVersion}"
implementation "com.blankj:utilcode:${cfgs.utilcodeVersion}"

2、读取gradle.properties

属性:

isModule=false

读取:

在Module 的build.gradle 中 

isModule.toBoolean() 或者 直接取isModule就可以了

3、读取local.properties

Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def sdkDir = properties.getProperty('sdk.dir')
def ndkDir = properties.getProperty('ndk.dir')

举例:同一套分支,多个项目同时使用,动态设置版本号等信息

第一步:在gradle.properties中添加属性 

CUR_PROJECT=UGA

第二步:在App下的build.gradle中写一个动态获取的方法

def getCurProjectVersionName(){
    if (CUR_PROJECT.equals("UGA")) {
        return "2.0.5"
    } else {
        return "2.3.1"
    }
}

def getCurProjectVersionCode() {
    if (CUR_PROJECT.equals("UGA")) {
        return 2000005
    } else {
        return 2003001
    }
}

第三步:调用方法获取版本信息

defaultConfig {
    versionCode getCurProjectVersionCode()
    versionName getCurProjectVersionName()
    signingConfig signingConfigs.config
    multiDexEnabled true
}

你可能感兴趣的:(Android,总结类)