Change apk name with Gradle

Lecho's solution doesn't work for Android Gradle Plugin 0.14.3+ because of removal of deprecated APIS: http://tools.android.com/tech-docs/new-build-system

Almost 1.0: removed deprecated properties/methods

...

  • Variant.packageApplication/zipAlign/createZipAlignTask/outputFile/processResources/processManifest (use the variant output)

The following works for me:

def appendVersionNameVersionCode(variant, defaultConfig) {
    variant.outputs.each { output ->
        if (output.zipAlign) {
            def file = output.outputFile
            def fileName = file.name.replace(".apk", "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk")
            output.outputFile = new File(file.parent, fileName)
        }

        def file = output.packageApplication.outputFile
        def fileName = file.name.replace(".apk", "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk")
        output.packageApplication.outputFile = new File(file.parent, fileName)
    }
}

As CommonsWare wrote in his comment, you should call appendVersionNameVersionCode only for staging variants. You can easily do that, just slightly modify your appendVersionNameVersionCode method, for example:

def appendVersionNameVersionCode(variant, defaultConfig) {
    //check if staging variant
    if(variant.name == android.buildTypes.staging.name){
        if(variant.zipAlign) {
            def file = variant.outputFile
            def fileName = file.name.replace(".apk", "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk")
            variant.outputFile = new File(file.parent, fileName)
        }

    def file = variant.packageApplication.outputFile
    def fileName = file.name.replace(".apk", "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk")
    variant.packageApplication.outputFile = new File(file.parent, fileName)
    }
}

For newer android studio Gradle

AppName is your app name you want so replace it
variantName will be default Selected variant or flavor
Date will Today's date, So need to do any changes just paste it

applicationVariants.all { variant ->
    variant.outputs.all {
        def variantName = variant.name
        def versionName = variant.versionName
        def formattedDate = new Date().format('dd-MM-YYYY')
        outputFileName = "AppName_${variantName}_D_${formattedDate}_V_${versionName}.apk"
    }
}

Output:

AppName_release_D_26-04-2021_V_1.2.apk