8

I'm using Gradle to compile my Android project:

buildTypes {
    release {
        signingConfig signingConfigs.release 
        applicationVariants.all { variant ->
            def file = variant.outputFile
            def fileName = file.name
            fileName = fileName.replace(".apk", "-renamed.apk")
            variant.outputFile = new File(file.parent, fileName)
        }
    }
}

Not all output files are renamed, it always skips 1 file. Why?

myapp-debug-unaligned-renamed.apk    <-renamed, OK!
myapp-release.apk                    <-NOT renamed, WRONG!
myapp-release-unaligned-renamed.apk  <-renamed, OK!
Marcel Bro
  • 4,907
  • 4
  • 43
  • 70
Seraphim's
  • 12,559
  • 20
  • 88
  • 129

3 Answers3

17

I solved using this code:

buildTypes {
    release {
        signingConfig signingConfigs.release 
    }

    applicationVariants.all { variant ->
        def apk = variant.packageApplication.outputFile;
        def newName = apk.name.replace(".apk", "-renamed.apk");
        variant.packageApplication.outputFile = new File(apk.parentFile, newName);
        if (variant.zipAlign) {
            variant.zipAlign.outputFile = new File(apk.parentFile, newName.replace("-unaligned", ""));
        }
    }
}

The block applicationVariants.all {...} is now outside the release {...} block.

I think variant.zipAlign.outputFile makes the difference.

Seraphim's
  • 12,559
  • 20
  • 88
  • 129
  • 2
    The syntax has changed with the 1.0.0 version of the gradle plugin. See updated solution here: http://stackoverflow.com/questions/23693309/renaming-apk-in-gradle/27369185#27369185 – Nebu Dec 09 '14 at 00:02
4

There should be 3 output APK files when using your build.gradle configuration: debug unsigned unaligned, release signed aligned and release signed unaligned. There are two variables for applicationVariant to deal with output files: outputFile and packageApplication.outputFile, the former is used for zipalign and the later is used in general case.

So the proper way to rename all the files will be like this:

android.applicationVariants.all { variant ->
    if (variant.zipAlign) {
        def oldFile = variant.outputFile;
        def newFile = oldFile.name.replace(".apk", "-renamed.apk")
        variant.outputFile = new File(oldFile.parent, newFile)
    }

    def oldFile = variant.packageApplication.outputFile;
    def newFile = oldFile.name.replace(".apk", "-renamed.apk")
    variant.packageApplication.outputFile = new File(oldFile.parent, newFile)
}
shakalaca
  • 1,692
  • 12
  • 5
-1

I simplified it by removing one of your lines but essentially you need to change it like so:

android {

    buildTypes {
    ...
    }

    applicationVariants.all { variant ->
        def file = variant.outputFile
        def fileName = file.name.replace(".apk", "-renamed".apk")
        variant.outputFile = new File(file.parent, fileName)
    }
}
dinobud
  • 31
  • 1
  • 4