This tutorial will teach you an alternative way to add library project to your android project without using built-in user interface of Android Studio. Maybe this is an older way to do but in certain cases it is still relevant. Now many developers are migrating to gradle based build automation system and new open source libraries are hosted on online repositories. Still there are some rare library developers are reluctant to move their libraries to online repositories and developers are often confused how to add these libraries to their projects. This article is actually for such people.
Remember: Android Studio Projects are Modular
Here we use
Gradle, which is the Build Automation tool of Android Studio, to add library projects with a single line code. Android Studio Project has modular structure and we have a main module called “app” (you can see “app” module as a directory in the below picture). You can Modules are marked in dark color in IDE’s project explorer tab. There may be multiple modules in a Project. We can connect them together through Gradle, these connection is known as
What is your task?
- Make this library folder as a module of the Project
- Create dependency to it through Gradle
I am going to split these two tasks into multiple steps so you can understand them well.
STEP 1: Add Library Project To Root Folder
Copy library project folder to the root folder of your project.
Open settings.gradle file in the root of your project directory.
Where you can see something like this,
app” is the name of the main module. For ex: if your package name is com.example.app then app is your module.
Here you have to specify name of the library project.
include ':libraries:BaseGameUtils', ':app'
here i add
BaseGameUtils as project library.
Add library as a dependency to your module’s gradle file (build.gradle)
compile fileTree(dir: 'libs', include: ['*.jar'])
libraries” is the directory name where we put all library projects. You can also add them as separate folders it is up to you.
compile project(':libraries:BaseGameUtils') line make gradle compile its code and add it as a dependency. Please note the order how you add dependencies have importance.
The order you add in the dependency section is important. Gradle compiles the source code in the same order how you add them in the build.gradle file.
For example, If library ‘A’ depend on library ‘B’ then you have to add library ‘A’ before library ‘B’.
You Are Done!
Now the implementation has been completed. Final step is to gradle sync the project (click on the green down arrow button). The android studio IDE will automatically be asking you to synch if you made any changes to the gradle files.
Now you can use your library in your code.
All the best!