使用不同的VersionCode进行Debug / Release android gradle build

问题描述 投票:12回答:4

我想应用不同的VersionCode来制作apk文件。对于调试,仅将其修复为1,并释放defaultConfig中指定的任何数字。

下面的代码将mypackage-release-1.apk文件作为assembleRelease工件提供,这是不期望的。我期待mypackage-release-10111.apk

为什么行debug { defaultConfig.versionCode=1 }会影响assembleRelease工件?

defaultConfig {
    versionCode 10111
    versionName '2.5.4'
    minSdkVersion 10
    targetSdkVersion 21
}
signingConfigs {
    debug {
        project.ext.loadSign = false
        defaultConfig.versionCode = 1 // Why this value applied to assembleRelease?
    }
    release {
        project.ext.loadSign = true
        applicationVariants.all { variant ->
            variant.outputs.each { output ->
                def file = output.outputFile
                output.outputFile = new File(file.parent, file.name.replace(".apk", "-" + defaultConfig.versionCode + ".apk"))
            }
        }
    }
}
buildTypes {
    debug {
        signingConfig signingConfigs.debug
    }
    release {
        signingConfig signingConfigs.release
    }
}
android android-gradle build.gradle
4个回答
7
投票

我也是,但我认为defaultConfig.versionCode是在build.gradle编译时设置的。它是全局静态变量,在编译时分配,而不是运行时。

我想我们可以拦截gradle任务执行,并在运行时修改defaultConfig.versionCode


goooooooogle之后,我发现这个适用于我:https://gist.github.com/keyboardsurfer/a6a5bcf2b62f9aa41ae2


7
投票

晚会......

在任何任务执行之前评估整个gradle文件,因此您在声明versionCode配置时基本上更改了默认的debug。没有直接的方法可以从versionCode重置buildType,但是另一个答案的链接可以通过声明构建变体的任务来实现。

android {
    ...
    defaultConfig {
         ...
    }
    buildTypes {
         ...
    }
    applicationVariants.all { variant ->
        def flavor = variant.mergedFlavor
        def versionCode = flavor.versionCode
        if (variant.buildType.isDebuggable()) {
            versionCode += 1
        }
        flavor.versionCode = versionCode
    }
}

1
投票

这是一个更新版本:

android {
  defaultConfig { ... }

  applicationVariants.all { variant ->
    if (variant.name == 'debug') {
      variant.outputs.each { output ->
        output.versionCodeOverride = 1
      }
    }
  }
}

1
投票

与Flavors一起使用:

applicationVariants.all { variant ->
    def flavor = variant.mergedFlavor
    def name = flavor.getVersionName()
    def code = flavor.getVersionCode()

    if (variant.buildType.isDebuggable()) {
        name += '-d'
        code = 1
    }

    variant.outputs.each { output ->
        output.versionNameOverride = name
        output.versionCodeOverride = code
    }
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.