androidandroid-gradle-pluginbuild.gradle

Use different VersionCode for Debug/Release android gradle build


I'd like to apply different VersionCode to make apk file. For debug only fix it to 1, and for release whatever number specified in defaultConfig.

Below code gives mypackage-release-1.apk file as assembleRelease artifact, which is not expected. I expected mypackage-release-10111.apk for that.

why the line debug { defaultConfig.versionCode=1 } affects assembleRelease artifact?

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
    }
}

Solution

  • Here's an updated version:

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