10

I wish to rename my apk from gradle. I have the following lines inside build

applicationVariants.all { variant ->      
            def file = variant.outputFile
            def filename = file.name.replace("SomeXXX", "SomeYYY")
            variant.outputFile = new File(file.parent, filename)

                    }

This successfully renames the apks but not the unaligned apks. Please someone throw some light on this.

Pulkit Sethi
  • 1,325
  • 1
  • 14
  • 22
  • Probably `applicationVariants` doesn't hold info about unaligned variants. But AFAIK it's quite easy to find unaligned variant when You know variant name. – Opal May 17 '14 at 07:53
  • 2
    related : http://stackoverflow.com/questions/16787493/android-gradle-build-renaming-the-apk/16794456#16794456 – ben75 Sep 11 '14 at 08:14

1 Answers1

16

The gradle plugin has moved on since you posted this, however to get this working on with the current plugin (v1.0.0), you can use the following:-

    variant.outputs.each { output ->
        def alignedOutputFile = output.outputFile
        def unalignedOutputFile = output.packageApplication.outputFile

        // Customise APK filenames (to include build version)
        if (variant.buildType.zipAlignEnabled) {
            // normal APK
            output.outputFile = new File(alignedOutputFile.parent, alignedOutputFile.name.replace(".apk", "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk"))
        }
        // 'unaligned' APK
        output.packageApplication.outputFile = new File(unalignedOutputFile.parent, unalignedOutputFile.name.replace(".apk", "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk"))
    }
Nebu
  • 1,352
  • 1
  • 14
  • 21
  • Thank you for the answer. But where does the above snippet go? When I post it within android {...} in my build.gradle file I get a Cannot resolve symbol "variant" - running gradle 2.2.1 and Android Studio 1.0.2 – AgentKnopf Jan 12 '15 at 13:40
  • 3
    @Zainodis that should go in the buildTypes section. – karl Jan 16 '15 at 16:59
  • @karl thank you a lot for your comment! Meanwhile I realized that the gradle editor in Android studio is not quite finished yet, that's why the variant variable couldnt be resolved. – AgentKnopf Jan 17 '15 at 09:57
  • 1
    This doesn't work for me using gradle 2.12 from the command line. I put the snippet under buildTypes, and I get `Could not find property 'outputs' on BuildType_Decorated{name=variant...` – Orion Edwards Apr 05 '16 at 21:24