The Gradle build system for Android can definitely take some getting used to. I suspect as time goes on, more of this will become automated. For now, though, you may wonder how to add an android library project, perhaps from some Git repository in the world, to your project. If it doesn’t have a maven build, or a Gradle build script, you will have a problem with this. If the artifact was published as an .aar you can used the standard dependency mechanism. This is for those situations where you can’t do this.
First, create a directory under your top level project called
libraries and either clone the Git repository, or add a Git submodule inside this directory for the library project you want to include.
Here’s an example
.gitmodules file for adding some submodules to an example library project.
[submodule "libraries/AndroidCharts"] path = libraries/AndroidCharts url = https://github.com/nealsanche/AndroidCharts [submodule "libraries/ViewPagerIndicator"] path = libraries/ViewPagerIndicator url = https://github.com/JakeWharton/Android-ViewPagerIndicator.git
Now, you need to edit your top level
settings.gradle file and add these projects to your module list:
AndroidCharts already contains a
build.gradle which builds the project, so we don’t have to add one.
If you need to add a Gradle build file for a project that doesn’t already have one, there’s a way to do that too. Add the following lines to your top level build.gradle file, to add a build for a project. Substitute the name of the project.
The following shows how you would build the ViewPagerIndicator library
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
I also found that you may need to add an
allprojects section to your top level
build.gradle to set up the maven repositories. As well as a
buildscript section to load the gradle build tools. Something like the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
I’ll have to spend some time rewriting this, the next time I write a project from scratch and see if I can come up with a smaller set of lines that work.
Now, you’ve set up the build.gradle files so that the library project modules will be built, but you need to also add dependencies to your main project. Inside your
build.gradle file in your main module, add some lines to your dependencies section:
1 2 3 4 5 6 7 8 9 10
In lines 2 and 3 you can see the
compile project('...') directives that ensure that Gradle will add the library projects as a dependency to your APK.
I’m writing this because I need a nice place to look this up when I forget it again for the 50th time. I’m sure you’ll forget it too, and will need a refresher course, just Like I have.