Friday, July 17, 2015

How to use an external project as a library project in Android Studio

We have 2 Android projects:
MyApplication is the project that produces apk and to be run on mobile devices;
Dependency is a library project that contains useful classes such as Fragments, Services, Util classes to be used by MyApplication.

The structure of these 2 projects are like this:
MyApplication
  |--build.gradle
  |--settings.gradle
  |--app
  |    |--build.gradle
Dependency
  |--build.gradle
  |--settings.gradle
  |--app
  |    |--build.gradle

First of all, we need to make sure that the gradle plugin of Dependency/app/build.gradle is library instead of application. The first line of the build.gradle file should be this:


apply plugin: 'com.android.library'

Then we go back to the MyApplication project, find the settings.gradle file under the project directory(MyApplication/settings.gradle), edit it to include our Dependency project by adding the lines like this:


include ':library-project-name'
project(':library-project-name').projectDir = new File(settingsDir, '../Dependency/app/')

the second parameter of File(.., ..) is a directory path pointing to the build.gradle file of the app module of the library project.


The last step is to configure the build.gradle file of the app module of the MyApplication project in order to add the library project to its dependencies.

We go to MyApplication/app/build.gradle file and add a line to the dependencies block.


dependencies{
   ........
   compile project(':library-project-name')
}

All done, feel free to use any classes in the Dependency library project in your MyApplication project from this point on.

No comments:

Post a Comment