How to access versionCode from task in Gradle Expe

2019-06-05 07:14发布

问题:

I would like to access versionCode and versionName in defaultConfig from a gradle task. I am using the experimental gradle plugin. I tried model.android.defaultConfig.versionCode but it doesn't recognise android...

apply plugin: 'com.android.model.application'

apply from: "../config.gradle"
apply from: "../gitversion.gradle"
def config = ext.configuration

model {
    android {
        compileSdkVersion = config.compileSdkVersion
        buildToolsVersion = config.buildToolsVersion

        defaultConfig {
            applicationId = 'eu.tss.apitest'
            minSdkVersion.apiLevel = config.minimumSdkVersion
            targetSdkVersion.apiLevel = config.targetSdkVersion
            defaultConfig {

            versionCode = 1
            versionName = '1.0'
            ext.printVersions(versionCode,versionName)
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles.add(file('proguard-android.txt'))
            }
        }

    }
   android.lintOptions {

        abortOnError false
    }
}

dependencies {
    println rootProject.getName()
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile project(':tssapiandroid')
    compile project(path: ':tssuielements')
}

task printVersions{

    //I would like to access versionCode here:)
}

回答1:

Create method in your build.gradle:

def getVersionCode = { ->
    // calculate versionCode code or use hardcoded value
    return 1
}

Use this method in defaultConfig:

android {
    defaultConfig {
        versionCode getVersionCode()
    }
}

Use the same method in your custom task:

task printVersions{
    print "Version code is " + getVersionCode()
}

Alternative solution is to access versionCode property directly:

task printVersions{
    print "Version code is $project.android.defaultConfig.versionCode"
}


回答2:

String versioncode = "-1";

PackageManager manager = context.getPackageManager();
PackageInfo info = null;
try {
    info = manager.getPackageInfo(context.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

info.versionCode;