Gradle makes easy to include external binaries or other library modules to your build as dependencies. The dependencies can be located on your machine or in a remote repository, and any transitive dependencies they declare are automatically included as well. Dependencies are usually managed at the Module-level inside dependencies block in build.gradle file.
Once you have lots of modules, build.gradle file can quickly get messy from dependencies. So In this article, I’ll show a quick way of making Gradle clean and easy to maintain.
Manage dependencies versions
Let’s say our Module-level build.gradle looks like as mentioned below in that you can see most of the libraries have similar library version.
It is very difficult to manage versions of different libraries. Here we can leverage Gradle’s extra property. For this Gradle provides ext block where we can define our common property values and use those property values in dependencies.
In above sample code ext block contains two property field playServiceVersion and supportLibraryVersion. Notice that instead of version number, we added $ with its version property and also changed single quotes to double quotes.
When you have multiple modules and you want to use similar version to them also then just move ext block from Module-level build.gradle to Top-level (root) build.gradle.
Now your different modules build.gradle will looks like:
Here “com.android.support:appcompat-v7:$supportLibraryVersion” changed to “com.android.support:appcompatv7:$rootProject.supportLibraryVersion”
This is just the basic use of ext block. You can also configure other common properties like — versionName, versionCode, minSdkVersion etc in it.
Manage File Dependencies
To add the JARs dependency in your module you simply kept it in the libs folder and add the below compile dependency:
Adding specific JARs from defined folder
Gradle also provides the flexibility to configure and only import the JARs from our choice and also from defined directory. Let’s say we want “first.jar”, “second.jar” from “mylibrary” directory. This directory is located at project level. So this can be achieve like:
Let’s say we have kept AAR file (mylib.aar) in libs folder, so in Top level build.gradle we need to specify flatDir as following:
And add the below compile dependency in the Module level build.gradle:
This is all about Gradle dependencies. In general to maintain your Gradle, define your properties in the root level/ top level build.gradle and use it into different modules. You can also refer my previous articles on Gradle for more details.
Thanks for reading. To help others please click ❤ to recommend this article if you found it helpful.
Check out my blogger page for more interesting topics on Software development at http://androidjavapoint.blogspot.in
See you soon in the next article!