简体   繁体   中英

Android - Only execute Gradle task on release build variant

I am trying to configure my build.gradle file to only execute a gradle task when the release build variant is selected. So far, my task always gets executed, whether it is in my debug or release build types or signing configs. I have tried adding my task inside an applicationsVariants block and check if it is the release variant, but it just loops through all variants.

applicationVariants.all { variant ->
            variant.outputs.each { output ->
        ...
    }
}

I know that both the debug and release tasks always run for whichever build variant you choose. Is it possible to execute some code only when creating a build for release? If so, where does that code go? Thanks!

I have read through every Stackoverflow question on this, but none of the answers really did I am wanting. My end goal is when I select the "release" build variant for a Play Store build, a message is posted to our server. I do not want this to happen when just debugging.

Add doFirst or doLast for the build type you are interested in.

android.applicationVariants.all {  variant ->
    if ( variant.buildType.name == "release"){
        variant.assemble.doLast { // Can also use doFirst here to run at the start.
            logger.lifecycle("we have successfully built $v.name and can post a messaage to remote server")
        }
    }
}

I had to do something like this to check build version:

buildTypes {
    applicationVariants.all { variant ->
        variant.outputs.each {output ->
            def project = "AppName"
            def separator = "_"
            /*def flavor = variant.productFlavors[0].name*/
            def buildType = variant.variantData.variantConfiguration.buildType.name
            def versionName = variant.versionName
            def versionCode = variant.versionCode
            def date = new Date();
            def formattedDate = date.format('yyyyMMdd_HHmm')
            if (variant.buildType.name == "release"){
                def newApkName = project + separator + "v" + versionName + separator + versionCode + separator + buildType + separator + formattedDate + ".apk"
                output.outputFile = new File(output.outputFile.parent, newApkName)
            }
            if (variant.buildType.name == "debug"){
                def newApkName = project + separator + "v" + versionName + separator + versionCode + separator + buildType + ".apk"
                output.outputFile = new File(output.outputFile.parent, newApkName)
            }
        }
    } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM