Android – Share code between multiple applications

Physical Path way

It may work well when you have a common drive location among code contributors. If you are only the one who maintain this library for a  different projects then this can your favourite option.

Open your app settings.gradle and add these lines:

include ':app'
include ':networkservices'
include ':common'

project (':networkservices').projectDir = new File('/Users/mramit/Documents/gits/lib/networkservices')
project (':common').projectDir = new File('/Users/mramit/Documents/gits/lib/common')

How to use it in app/ library?

All you have to do is add a dependency of this library: 

dependencies {
    compile project(':networkservices')

AAR way

Just like you create Jar for Java, you can also do the same for Android. However, it does not work well when you have resources to share e.g. string.xml

Instead of a Jar, the recommendation is to create an AAR file a.k.a Android Archive.

Why aar?

aar file is developed on top of jar file. It was invented because something Android Library needs to be embedded with some Android-specific files like AndroidManifest.xml, Resources, Assets or JNI which are out of jar file’s standard. So aar was invented to cover all of those things. Basically it is a normal zip file just like jar one but with different file structure. jar file is embedded inside aar file with classes.jar name. And the rest are listed below:

– /AndroidManifest.xml (mandatory)
– /classes.jar (mandatory)
– /res/ (mandatory)
– /R.txt (mandatory)
– /assets/ (optional)
– /libs/*.jar (optional)
– /jni/<abi>/*.so (optional)
– /proguard.txt (optional)
– /lint.jar (optional)

Then when to use to JAR?

If you are planning to provide any res in your common repo then the recommendation is *not* to use JAR.
Otherwise, you may go for Jar.

How to create aar ?

Requirement is it should be a library, and you have a library plugin applied in your library gradle.

apply plugin: ''

There is nothing else that needs to be done. When you will build with the gradle task, go to build/outputs/aar/ folder to copy and share this aar file.

How to use aar in your app or library?

Put the aar file in the libs directory (create it if needed), then, add the following code in your build.gradle :

dependencies {
  compile(name:'nameOfYourAARFileWithNoExtension', ext:'aar')
      dirs 'libs'