使用Gradle设置Android应用版本

Sla*_*ava 34 android gradle android-studio build.gradle android-gradle-plugin

我正在尝试使用Gradle来设置应用程序的名称.请看一下build.gradle的这个片段:

android {
    ...
    defaultConfig {
        ...
        versionCode getVersionCode()
        versionName getVersionName()
        ...
    }
    ...
}

...

int getVersionCode() {
    return 1
}

def getVersionName() {
    return "1.0"
}
Run Code Online (Sandbox Code Playgroud)

Android Studio说

   'versionCode' cannot be applied to 'java.lang.Integer'
   'versionName' cannot be applied to 'java.lang.String'
Run Code Online (Sandbox Code Playgroud)

当我在设备上安装应用程序时,它根本没有versionCode和versionName.

问题很明显,但我不知道如何解决它.
请指教.

Gab*_*tti 49

它不能解决您的问题,但它可以是一个不同的解决方案.

您可以在根项目中使用gradle.properties并定义:

VERSION_NAME=1.2.1
VERSION_CODE=26
Run Code Online (Sandbox Code Playgroud)

然后在build.gradle中,您可以使用:

versionName project.VERSION_NAME
versionCode Integer.parseInt(project.VERSION_CODE)
Run Code Online (Sandbox Code Playgroud)

  • 注意:在更新使用更新的构建工具之前,这非常有用!之后我注意到我的版本代码未设置,并且Android Studio中的Integer.parseInt标记为未知.现在需要:**project.VERSION_CODE.toInteger()** (10认同)

kei*_*axx 29

EDITED

要动态定义您的应用版本,请使用def指定自定义方法并将其调用,如下所示:

def computeVersionName() {
    return "2.0"
}

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        versionCode 12
        versionName computeVersionName()
        minSdkVersion 16
        targetSdkVersion 16
    }
}
Run Code Online (Sandbox Code Playgroud)

请看这里了解更多.

确保不要使用可能与给定范围内的现有getter冲突的函数名称.例如,defaultConfig { ... }调用getVersionName()将自动使用getter defaultConfig.getVersionName()而不是自定义方法.

  • 该链接确实提到了`注意:不要使用可能与给定范围内的现有getter冲突的函数名.例如,调用getVersionName()的实例defaultConfig {...}将自动使用defaultConfig.getVersionName()的getter而不是自定义方法.所以尝试使用不同的方法名称. (3认同)

Phi*_*o99 11

这是我根据JakeWharton的想法使用的build.gradle:

apply plugin: 'com.android.application'
def versionMajor = 1
def versionMinor = 2
def versionPatch = 0

def gitVersion() {
    def counter = 0
    def process = "git rev-list master --first-parent --count".execute()
    return process.text.toInteger()
}

repositories {
    mavenCentral()
}

android {
    compileSdkVersion 19
    buildToolsVersion '19.1.0'


    defaultConfig {
        applicationId 'my.project.com'
        minSdkVersion 14
        targetSdkVersion 19
        versionCode gitVersion()
        versionName "${versionMajor}.${versionMinor}.${versionPatch}"
    }
    ....
}
Run Code Online (Sandbox Code Playgroud)