Autoincrement VersionCode with gradle extra properties

前端 未结 16 2213
逝去的感伤
逝去的感伤 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条回答
  •  Happy的楠姐
    2020-11-27 09:41

    I would like to read the versionCode from an external file

    I am sure that there are any number of possible solutions; here is one:

    android {
        compileSdkVersion 18
        buildToolsVersion "18.1.0"
    
        def versionPropsFile = file('version.properties')
    
        if (versionPropsFile.canRead()) {
            def Properties versionProps = new Properties()
    
            versionProps.load(new FileInputStream(versionPropsFile))
    
            def code = versionProps['VERSION_CODE'].toInteger() + 1
    
            versionProps['VERSION_CODE']=code.toString()
            versionProps.store(versionPropsFile.newWriter(), null)
    
            defaultConfig {
                versionCode code
                versionName "1.1"
                minSdkVersion 14
                targetSdkVersion 18
            }
        }
        else {
            throw new GradleException("Could not read version.properties!")
        }
    
        // rest of android block goes here
    }
    

    This code expects an existing version.properties file, which you would create by hand before the first build to have VERSION_CODE=8.

    This code simply bumps the version code on each build -- you would need to extend the technique to handle your per-flavor version code.

    You can see the Versioning sample project that demonstrates this code.

提交回复
热议问题