The Good the Bad and the Ugly way to share library projects in Android studio

George Argyrakis | 28/08/2016 | Android studio, programming, gradle, tips

A common problem

Suppose you have a project for your awesome application called “MyAwesomeApp”. You are developing in android studio and using a source control (github, bitbucket, VSO etc). Inside that app you have a library module that does something special (let’s call it “SpecialLib”)

Now you want to use the same functionality that the SpecialLib provides in a new project called “MyNewApp” project. You have also to make some modification to the library and test them in the new project.

Let’s see the alternatives for doing this.


The Bad

Copy paste the code from MyAwesomeApp project to MyNewApp project, make the changes and you are ready to go. The fastest but the of course worst way to do it. (The reason is left as an exercise for the reader)

The Ugly

One other solution would be to:

  1. Copy paste the compiled SpecialLib jar/aar from MyAwesomeApp project into MyNewApp project
  2. Add a dependency of MyNewApp to SpecialLib
  3. Make any changes in SpecialLib in MyAwesomeApp project
  4. Build the jar/aar and copy paste it in MyNewApp project
  5. Test the changes.
  6. If more changes / bug fixes are required go to step 3

With this way you can keep a versioning of the library and you can relatively easy use it in new projects without modifications. In our scenario though, in which development on the library is required, would be a quite cumbersome procedure.

One slight improvement would be to replace step 3 with the use of a maven repository but this does not solve the problem when changes to the library are required.

And the Good

The best solution is so simple as to just reference SpecialLib as an external library project. Here is how to achieve it.

In MyNewApp settings.gradle add those two lines (assuming that MyNewApp and MyAwesomeApp projects are under the same folder)

include ': SpecialLib'
project(': SpecialLib').projectDir = new File(settingsDir, '../MyAwesomeProject/SpecialLib ')

And of course do not forget to add a dependency of MyNewApp to SpecialLib, by adding the following in build.gradle

dependencies {
compile project(':SpecialLib')

Now you can change the code and build SpecialLib directly from MyNewApp. If you use source control the changes in SpecialLib will be commited in MyAwesomeApp project.

You can also combine this solution with a maven repository for uploading the final library.