Android Libraries with Gradle and Android Studio

The new Gradle-based build system for Android apps is a huge improvement over older eclipse, ant, and maven-based approaches. It has a simple declarative syntax and makes building different variants of your app (e.g. staging vs. production) very easy. Gradle is also the default build system for the new Android Studio IDE, so there are lots of good reasons to migrate your apps over.

The new system also finally provides an official way to package up Android library dependencies, however I’ve seen a lot of confusion on IRC and G+ about how this works, so here’s a quick guide.

ActionBarSherlock already has gradle build scripts, but the archive is not yet published on Maven Central so you’ll have to build from source:

$ git clone -b dev https://github.com/JakeWharton/ActionBarSherlock.git
$ cd ActionBarSherlock/actionbarsherlock
$ gradle assemble

This will create an archive at build/libs/actionbarsherlock-4.3.2-SNAPSHOT.aar.

Ideally we could just copy this into our app’s libs/ directory and add a File dependency, but unfortunately this currently only works for jar files.

Instead, we’ll “install” the archive into a local maven repository inside our app:

$ mvn install:install-file \
    -DgroupId=com.actionbarsherlock \
    -DartifactId=actionbarsherlock \
    -Dversion=4.3.2-SNAPSHOT \
    -DgeneratePom=true \
    -Dpackaging=aar \
    -Dfile=build/libs/actionbarsherlock-4.3.2-SNAPSHOT.aar \
    -DlocalRepositoryPath=/path/to/myapp/libs

(Set localRepositoryPath to the full path of your app’s libs directory.)

Now in your app’s build.gradle simply add libs as a maven repo and add the dependency:

repositories {
    mavenCentral()
    maven { url 'libs' }
}

dependencies {
    compile 'com.actionbarsherlock:actionbarsherlock:4.3.2-SNAPSHOT'
}

That’s it! Be sure to commit the entire libs directory to source control so other developers (and your CI server) can easily build your project. You can also choose to host dependencies in your own remote maven repository, but that’s overly complex for most projects.

ActionBarSherlock is a good example of how to add Gradle support to a library that primarily uses a dfferent build system and that does not yet have a published aar. I’ve done the same thing for the Facebook SDK here. Between those examples and the official docs, you should have no trouble creating aar archives for any other project you need.

Hope this helps someone!

← Read More