Autoincrement VersionCode with gradle extra properties

前端 未结 16 2197
逝去的感伤
逝去的感伤 2020-11-27 08:47

I\'m building an Android app with gradle. Until now I used the Manifest file to increase the versionCode, but I would like to read the versionCode from an external file and

16条回答
  •  -上瘾入骨i
    2020-11-27 09:51

    Examples shown above don't work for different reasons

    Here is my ready-to-use variant based on ideas from this article:

    android {
        compileSdkVersion 28
    
        // https://stackoverflow.com/questions/21405457
    
        def propsFile = file("version.properties")
        // Default values would be used if no file exist or no value defined
        def customAlias = "Alpha"
        def customMajor = "0"
        def customMinor = "1"
        def customBuild = "1" // To be incremented on release
    
        Properties props = new Properties()
        if (propsFile .exists())
            props.load(new FileInputStream(propsFile ))
    
        if (props['ALIAS'] == null) props['ALIAS'] = customAlias else customAlias = props['ALIAS']
        if (props['MAJOR'] == null) props['MAJOR'] = customMajor else customMajor = props['MAJOR']
        if (props['MINOR'] == null) props['MINOR'] = customMinor else customMinor = props['MINOR']
        if (props['BUILD'] == null) props['BUILD'] = customBuild else customBuild = props['BUILD']
    
        if (gradle.startParameter.taskNames.join(",").contains('assembleRelease')) {
            customBuild = "${customBuild.toInteger() + 1}"
            props['BUILD'] = "" + customBuild
    
            applicationVariants.all { variant ->
                variant.outputs.all { output ->
                    if (output.outputFile != null && (output.outputFile.name == "app-release.apk"))
                        outputFileName = "app-${customMajor}-${customMinor}-${customBuild}.apk"
                }
            }
        }
    
        props.store(propsFile.newWriter(), "Incremental Build Version")
    
        defaultConfig {
            applicationId "org.example.app"
            minSdkVersion 21
            targetSdkVersion 28
            versionCode customBuild.toInteger()
            versionName "$customAlias $customMajor.$customMinor ($customBuild)"
    
            ...
        }
    ...
    }
    

提交回复
热议问题