22

I am learning to build Android shared libraries that can be used with different projects. I got a few questions regarding this subject. Before I go into the questions, below is what I have done so far:

  • Create a library project
  • Create another application project and import above library as a module

My questions are:

  • Is the library project's code automatically synchronized with the one imported into application projects? How it can be achieved?
  • If not, what else I can do to make sure I just need to update the shared library once?

I am using Android Studio IDE.

Thank you,

Ralphilius
  • 1,746
  • 2
  • 16
  • 28

2 Answers2

42

Ah yes, this can be very helpful in many cases. You can do the following to achieve this.

Let's say you have two projects - MyApplication and MyLibraryDemo containing the library module libmodule with the following paths:

MyApplication - "/../AndroidStudioProjects/MyApplication"

MyLibraryDemo - "/../AndroidStudioProjects/MyLibraryDemo"

libmodule - "/../AndroidStudioProjects/MyLibraryDemo/libmodule"

And let's say you are trying to use libmodule in MyApplication. Then, in your settings.gradle of your MyApplication project, do this

include ':app', ":libmodule"
project(':libmodule').projectDir = new File(settingsDir, '../MyLibraryDemo/libmodule')

You may have to make relevant corrections, but I hope the idea of linking another module is clear.

All the best :)

Awanish Raj
  • 1,939
  • 16
  • 17
  • This works like a charm. Two modules are automatically sync'ed, I don't need to open both of them when I want to update the shared module. – Ralphilius Jul 23 '15 at 18:18
  • 7
    What is `:app` folder and `settingsDir` here – viper Oct 27 '16 at 04:36
  • Is there a way to include the external projects but not to include the full path so they can be used on other PCs as well? – Esteban Sep 11 '17 at 11:52
  • @Esteban You can use the relative path to the other project as shown in the answer – Awanish Raj Sep 15 '17 at 11:51
  • 5
    For me the subproject indeed builds, but I cannot reference it as a dependency `Error:Unable to find module with Gradle path ':libmodule' (needed by module 'app'.)` when I declare it like this `compile project(':libmodule')` – Michał Klimczak Oct 24 '17 at 18:55
  • Just in case someone is looking for a Kotlin version: project(":libmodule").projectDir = File("../MyLibraryDemo/libmodule") – Emanuel Moecklin Apr 13 '21 at 15:54
7

Importing a module from outside of your application project creates a copy of the library inside of your application. If your system supports it, creating a symbolic link will allow you to have only one copy of the code.

Otherwise, you can move the entire library project into your application and add it to your settings.gradle.

If you wish to have separate git repositories for both of these projects, look into using git submodules.

afathman
  • 5,993
  • 2
  • 20
  • 28