Proguard Configuration in Cordova

July 14th 2017 Proguard Cordova Android

Proguard is an optimizer and obfuscator for Java code. It can make your Android applications smaller and faster while also somewhat protecting them from reverse engineering. It can easily be enabled with only a few entries in the Gradle build script. In Cordova applications, the build script is regenerated on each build, therefore you'll need a plugin to add the required entries to it unless you want modify it by hand every time.

Of course, you can find a plugin which will enable Proguard for you. IBM's Mobile First plugin also does that, so you don't even need a specialized plugin, if you're using it. However, things get more complicated if you need to modify the default Proguard configuration, which is included in the plugin.

This is not as rare a case as you might think. For example, if you're using the Cordova GoogleMaps plugin, additional exceptions are required in the Proguard configuration file for it to work. Although the requirement is documented on GitHub, the plugin does not modify the build script on its own. It leaves it up to you.

Again, you'll need to do it through a plugin to persist the modification across builds. You have three options available:

  • You can fork the Proguard plugin and add the exceptions to its configuration file.
  • You can fork the GoogleMaps plugin and add a Proguard configuration to it.
  • You can create a new plugin containing only the required Proguard configuration.

The first option is very straightforward and requires you to only paste the following line to the proguard-custom.txt file:

-keep public class * extends plugin.google.maps.MyPlugin
-keepclassmembers public class plugin.google.maps.GoogleMaps {*; }
-keepclassmembers public class * extends plugin.google.maps.MyPlugin { *; }

The other two options require you to create a new file containing only these very same lines (e.g named proguard-googlemaps.txt in the root of the plugin).

Additionally you will need a build script snippet (e.g. named build-proguard.gradle in the root of the plugin):

android {
  buildTypes {
    release {
      proguardFile 'proguard-googlemaps.txt'
    }
  }
}

As the final step, you will need to add the following inside the <platform name="android"> element of plugin.xml:

<framework src="build-proguard.gradle"
           custom="true" type="gradleReference" />
<resource-file src="proguard-googlemaps.txt"
               target="proguard-googlemaps.txt"/>

This will make sure that the other two files will be correctly included in the final build process.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License