Rename Gradle’s Generated Files

After generating apk several times, I grew tired of having to rename the files from “app-release.apk”. So I set out to find a way to automatically rename release apk to appropriate name.

Add app name and timestamp when generating release apk

If you want to rename the app to the project name, you can do the following:

  1. Add the following lines to your top level gradle file:
    ext {
        appName = "SIMAMI"
    }
    
  2. Add the following lines to your android.buildTypes.release section of the app module’s gradle file:
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def formattedDate = new Date().format('yyyyMMddHHmmss')
            def newName = output.outputFile.name
            newName = newName.replace("app-", "$rootProject.ext.appName-") //"MyAppName" -> I set my app variables in the root project
            newName = newName.replace("-release", "-release-" + formattedDate)
            //noinspection GroovyAssignabilityCheck
            output.outputFile = new File(output.outputFile.parent, newName)
        }
    }
    

    It should look like the following screenshot:

    Screen Shot 2015-06-12 at 10.29.04 PM

  3. It’s done! You’ll just have to generate the release apk to check the result. Based on modifications above, my generated apk became: SIMAMI-release20150612220958.apk instead of plain old app-release.apk
Add version number to generated apk

It is quite simple to add version number to the generated apk. All you have to do is, add defaultConfig.versionName to the newName.replace() code. Mine is like this:

applicationVariants.all { variant ->
                variant.outputs.each { output ->
                    def formattedDate = new Date().format('yyyyMMddHHmmss')
                    def newName = output.outputFile.name
                    newName = newName.replace("app-", "$rootProject.ext.appName-")
                    newName = newName.replace("-release", "-release-" + formattedDate + "-" + defaultConfig.versionName)
                    output.outputFile = new File(output.outputFile.parent, newName)
                }

Using codes above, my apk became: SIMAMI-release-20150612225535-1.0.6.apk

Author: Arief Bayu Purwanto

Hello, my name is Arief Bayu Purwanto, a 24 years old father of a beautiful daughter. Interested in online programming, linux, games, and reading. Currently working on kapanlagi.com as junior developer. I live in a relatively quite and cool place called Malang. I'm available for some freelance stuff as well as some consulting job. You can see my portofolio for some previous task I've finished and some other information related to my capability. Btw, I'm plurking here.