Autoincrement VersionCode with gradle extra properties

前端 未结 16 2200
逝去的感伤
逝去的感伤 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条回答
  •  执笔经年
    2020-11-27 09:37

    The First Commented code will increment the number while each "Rebuild Project" and save the the value in the "Version Property" file.

    The Second Commented code will generate new version name of APK file while "Build APKs".

    android {
        compileSdkVersion 28
        buildToolsVersion "29.0.0"
        //==========================START==================================
        def Properties versionProps = new Properties()
        def versionPropsFile = file('version.properties')
        if(versionPropsFile.exists())
            versionProps.load(new FileInputStream(versionPropsFile))
        def code = (versionProps['VERSION_CODE'] ?: "0").toInteger() + 1
        versionProps['VERSION_CODE'] = code.toString()
        versionProps.store(versionPropsFile.newWriter(), null)
        //===========================END===================================
        defaultConfig {
            applicationId "com.example.myapp"
            minSdkVersion 15
            targetSdkVersion 28
            versionCode 1
            versionName "0.19"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
                //=======================================START===============================================
                android.applicationVariants.all { variant ->
                    variant.outputs.all {
                        def appName = "MyAppSampleName"
                        outputFileName = appName+"_v${variant.versionName}.${versionProps['VERSION_CODE']}.apk"
                    }
                }
                //=======================================END===============================================
            }
        }
    }
    

提交回复
热议问题