Android Library Gradle release JAR

While I haven't tried uploading the artifacts with a deployment to Sonatype (or even a local repo), here's what I managed to come up with a few weeks ago when trying to tackle the same problem.

android.libraryVariants.all { variant ->
  def name = variant.buildType.name
  if (name.equals(com.android.builder.core.BuilderConstants.DEBUG)) {
    return; // Skip debug builds.
  }
  def task = project.tasks.create "jar${name.capitalize()}", Jar
  task.dependsOn variant.javaCompile
  task.from variant.javaCompile.destinationDir
  artifacts.add('archives', task);
}

Then run the following:

./gradlew jarRelease

Another way to generate a jar from a library project through gradle is as follows:

In your library's build.gradle:

def jarName = 'someJarName.jar'

task clearJar(type: Delete) {
    delete "${project.buildDir}/libs/" + jarName
}

task makeJar(type: Copy) {
    from("${project.buildDir}/intermediates/bundles/release/")
    into("${project.buildDir}/libs/")
    include('classes.jar')
    rename('classes.jar', jarName)
}

makeJar.dependsOn(clearJar, build)

What we are doing here is just copying the classes.jar generated by the Android Gradle plugin. Be sure to look into your build directory for this file and see if its contents are in the way you want.

Then run the makeJar task and the resulting jar will be in library/build/libs/${jarName}.jar

The will have the class files according to your configuration for release. If you are obfuscating it, then the files in the jar will be obfuscated.