如何从Gradle Experimental Plugin中的任务访问versionCode

时间:2016-12-01 08:47:36

标签: android gradle groovy gradle-experimental

我想从gradle任务访问defaultConfig中的versionCode和versionName。我正在使用实验性gradle插件。我尝试过model.android.defaultConfig.versionCode,但它不识别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:)
}

2 个答案:

答案 0 :(得分:4)

select { background: transparent; width: 100%; padding: 5px; font-size: 16px; line-height: 1; border: 0; border-radius: 0; height: 59.6px; -webkit-appearance: none; -moz-appearance: none; appearance: none; padding-left: 17px; background: url('##Pathtoimg##') no-repeat 96% #ffffff; outline: 0; border-color:#fff; } 中创建方法:

build.gradle

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

中使用此方法
defaultConfig

在自定义任务中使用相同的方法:

android {
    defaultConfig {
        versionCode getVersionCode()
    }
}

替代解决方案是直接访问task printVersions{ print "Version code is " + getVersionCode() } 媒体资源:

versionCode

答案 1 :(得分:-1)

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;