Zhou Hao Zhou Hao - 2 months ago 38
Android Question

The best way to integrate third party library in Android studio

We can find some very good open source libraries for android. I want to know what is the best way to integrate them to our own projects in Android studio. Here are some basic methods:


  • Copy the source code and resource files into our own project. We need to change a lot of codes (the package name, and the name in xml,etc)

  • If jar files is provided, I just create libs folder for my project and copy the jar files inside. And add the jar file in Module setting's dependencies. But unfortunately I got a lot of error messages like "Gradle: Package com.google.gson doesn't exist".



Is there a general rule to add third party source or jar files into an existing android studio project? Thanks

Answer

I prefer to use central repository for dependencies management. So for gson 2.3 dependency you should add to gradle file:

  • Specify that you want to use maven central repository for your dependency

    repositories {jcenter()}

  • Add compile dependency to gson 2.3

    dependencies {compile 'com.google.code.gson:gson:2.3'}

Android Studio as well as your CI server should easily build your project now. And you can continue app development.

I prefer to use central repository for dependencies management because:

  • easier scope management - some libraries are only for testing, some should be included to apk and some are part of running environemnt (like android.jar itself)
  • easier transitive dependencies management - it is quite hard to collect libraries depednencies and if you use "jar-with-dependencies" you could get error "class already added" during dexing
  • lighter repository and easier dependency upgrade

Examples:

  • Robolectric jar should be used for unit testing only and shouldn't be part of apk itself
  • Repository is clean from different folders with jars, checkout takes much less. No needs to download and replace old jars with new jars

I should notice:

  • Not many libraries are in maven central and you should make some effort to use them such way in your project
  • You could much easier get to "class already added" error during dexing with central repository aproach
  • You can mix usage of dependencies from central repository and from lib folder, but I prefer to use only one way for simplicity