Running zipalign with zopfli recompression after building APK from command line to make it smaller

1.9k views Asked by At

As mentioned in Google Developers' article, it is now possible to recompress APK files using zopfli by running zipalign -z. In my case, a 200 KB reduction is observed on a 5.1 MB APK file.

Normally I build the APK using a custom shell script, by running gradle assembleRelease.

I want to run zipalign -z <the final apk> after the above command. However, zipalign is located in the build-tools/<build tools version> directory, which I can't locate it except by pulling out the <build tools version> from the build.gradle file and constructing the path manually.

Is it possible to run zipalign using the gradle command that automatically run the zipalign on the correct build-tools directory without me having to reconstuct the path?

For example a command such as gradle runBuildTools zipalign -z $FINAL_APK $FINAL_APK.out

1

There are 1 answers

2
Joe Rider On BEST ANSWER

The article that you linked to has been updated with the gradle task to add the zopfli compression to the end of the assembleRelease task.

//add zopfli to variants with release build type
android.applicationVariants.all { variant ->
  if (variant.buildType.name == 'release') {
    variant.outputs.each { output ->
        output.assemble.doLast {
            println "Zopflifying... it might take a while"
            exec {
                commandLine output.zipAlign.zipAlignExe,'-f','-z', '4', output.outputFile.absolutePath , output.outputFile.absolutePath.replaceAll('\\.apk$', '-zopfli.apk')
            }
        }
    }
  }
}