Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Extending The Gradle Build File In Apache Cordova 5.0+

TwitterFacebookRedditLinkedInHacker News

Apache Cordova 5.0 brought many changes, all of which are for the best, but many of which are a major inconvenience in terms of development or deployment. For example, previously I wrote about whitelisting external resources in Ionic Framework because by default everything is now blacklisted.

This time we’re going to explore the new default build system, Gradle. This build system is nothing new as I’ve written about it in the past, however, it is new when it comes to Apache Cordova and hybrid mobile application development.

You may run into library conflicts or need to do little customizations to your build process. We’re going to see how to do these things. Gradle is for Android only, so if you’re developing for iOS, feel free to move along.

So I was recently working with a PhoneGap library that previously worked great when Apache Cordova was using Apache Ant as the build system instead of Gradle. When trying to build, I was getting the following error with Gradle:

Error: duplicate files during packaging of APK

This is because two of the JAR files bundled with the library shared a common set of files, leading to conflict. The error had a little more too it. It gave me a recommendation of how to correct the problem.

I went and navigated to my project’s platforms/android directory and found the build.gradle file which is nothing new to me. However, in the file, it clearly states that it is auto-generated and that it should not be edited.

Great, so then how do we fix this duplication issue, or edit the build.gradle file in general?

Per the official Apache Cordova documentation, we need to make a build-extras.gradle file that sits next to the build.gradle file. After doing this, I added the following code to build-extras.gradle which is pretty standard when it comes to Gradle:

android {
    packagingOptions {
        exclude 'META-INF/ASL2.0'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
}

Basically, the files with conflicts in the PhoneGap plugin are now excluded.

Conclusion

If you find yourself in a complicated Gradle situation while using Apache Cordova 5.0 or higher, you can always extend the auto-generated build file to include your custom logic. You will need to add this to the platforms/android directory which could lead to complications when sharing code over Git, but overall it isn’t a big deal and will probably be corrected in the future.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.