Getting a JAR into Android Studio
Brian Marick writes:
I am stunned, as if struck by a ball-peen hammer, by how hard it is to say “use this jar” to Android Studio 1.0.2. If it’s even possible.
It’s certainly possible, and in a standard Android Studio project it is pretty easy. Whether it is the right solution, though, is another matter.
I would recommend that you do some poking around and see if the library
is offered as an artifact in some place like Maven Central. The
“Gradle, please” Web site can help
with this, or you can use the Project Structure dialog in Android
Studio itself (File > Project Structure from the main menu).
Specifically, the Dependencies tab for your module
(e.g., app
) has a similar search feature to what “Gradle, please” offers.
Just use the + button and choose a “library dependency”, then search.
Whether you find the artifact from “Gradle, please” or add it via
the Project Structure dialog, the result is pretty much the same:
a compile
statement added to your module’s build.gradle
file:
dependencies {
compile 'com.squareup.okhttp:okhttp:2.2.0'
// and perhaps other lines here
}
Using the artifact means that chained dependencies (e.g., the JAR
depends upon other JARs) are handled for you, and updating to a
newer version of the JAR is simply a matter of updating the version
number in the compile
statement. Plus, your version control system
is now tracking what version of the JAR you are using, as opposed
to checking in some random JAR binary.
But, suppose you have a random JAR (andataco.jar
), and you cannot
find an artifact for it.
If your module’s build.gradle
file has the standard new-project
dependencies
closure:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
}
then all you need to do is put the JAR in libs/
within the
module, and you are done. The compile fileTree()
statement
says “yo, Gradle, take all the .jar
things in libs/
and
compile ‘em into the project”. That will add the JAR to the
compile-time classpath and, for an Android project, also package
the JAR’s contents into your APK file.