87

I have downloaded some library sources and would like to export it as a Jar file using Android Studio. Is there a way to export to jar file using Android studio ?

edit:

The library I want to export as jar is an Android library. It's called "StandOut" and can be downloaded from GitHub. https://github.com/pingpongboss/StandOut

2
  • Please give more details on the library you want to export
    – gamag
    Commented May 26, 2013 at 20:06
  • I edited my question with the details of the Android library. Commented May 26, 2013 at 22:39

7 Answers 7

87
+50

It is not possible to export an Android library as a jar file. It is possible, however, to export it as aar file. Aar files being the new binary format for Android libraries. There's info about them in Google I/O, the New Build System video.

First, build the library in Android Studio or from command line issuing gradle build from your library's root directory.

This will result in <yourlibroot>/libs/build/yourlib.aar file.

This aar file is a binary representation of your library and can be added to your project instead of the library as a dependency project.

To add aar file as a dependency you have to publish it to the maven central or to your local maven repository, and then refer the aar file in your project's gradle.build file.

However, this step is a bit convoluted. I've found a good explanation how to do so here:

http://www.flexlabs.org/2013/06/using-local-aar-android-library-packages-in-gradle-builds

6
  • 2
    also having android-library depending on other android-library may break things up. Commented Jun 16, 2013 at 10:24
  • Does the res folder will be included in aar file ?
    – Bagusflyer
    Commented Mar 27, 2014 at 2:59
  • see @Wallmart_Hobo's answer below, it is possible and I can confirm the exported jar works fine in an eclipse android app project.
    – Pellet
    Commented May 27, 2014 at 2:28
  • 2
    I found my aar file included in this link: lib\build\outputs\aar
    – Simon
    Commented Nov 2, 2014 at 12:46
  • See this stackoverflow.com/questions/19034466/…
    – TeeTracker
    Commented Jan 20, 2015 at 11:33
44

I was able to build a library source code to compiled .jar file, using approach from this solution: https://stackoverflow.com/a/19037807/1002054

Here is the breakdown of what I did:

1. Checkout library repository

In may case it was a Volley library

2. Import library in Android Studio.

I used Android Studio 0.3.7. I've encountered some issues during that step, namely I had to copy gradle folder from new android project before I was able to import Volley library source code, this may vary depending on source code you use.

3. Modify your build.gradle file

// If your module is a library project, this is needed
//to properly recognize 'android-library' plugin
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.6.3'
    }
}

apply plugin: 'android-library'

android {
    compileSdkVersion 17
    buildToolsVersion = 17

    sourceSets {
        main  {
            // Here is the path to your source code
            java {
                srcDir 'src'
            }
        }
    }
}

// This is the actual solution, as in https://stackoverflow.com/a/19037807/1002054
task clearJar(type: Delete) {
    delete 'build/libs/myCompiledLibrary.jar'
}

task makeJar(type: Copy) {
    from('build/bundles/release/')
    into('build/libs/')
    include('classes.jar')
    rename ('classes.jar', 'myCompiledLibrary.jar')
}

makeJar.dependsOn(clearJar, build)

4. Run gradlew makeJar command from your project root.

I my case I had to copy gradlew.bat and gradle files from new android project into my library project root. You should find your compiled library file myCompiledLibrary.jar in build\libs directory.

I hope someone finds this useful.

Edit:

Caveat

Althought this works, you will encounter duplicate library exception while compiling a project with multiple modules, where more than one module (including application module) depends on the same jar file (eg. modules have own library directory, that is referenced in build.gradle of given module).

In case where you need to use single library in more then one module, I would recommend using this approach: Android gradle build and the support library

6
  • I found there is no way to include the res inside the jar. Is that possible?
    – Bagusflyer
    Commented Mar 27, 2014 at 2:59
  • 7
    In recent versions of Android studio requires one change: line should read ` from('build/intermediates/bundles/release/')`
    – Greg Ennis
    Commented Jun 28, 2014 at 2:46
  • @GregEnnis ya, but in my case it is creating a jar with my mobule name and the actual jar lies inside that jar . I have extracted the created jar with my module name like module_name.jar . Commented Jul 25, 2014 at 12:19
  • 6
    @bagusflyer, If you want res folder, an AAR file is exactly that - a JAR file with res folder support. Commented Aug 1, 2014 at 4:58
  • how to apply proguard to generate this jar? Commented Apr 21, 2015 at 10:02
38

Since Android Studio V1.0 the jar file is available inside the following project link:

debug ver: "your_app"\build\intermediates\bundles\debug\classes.jar

release ver: "your_app"\build\intermediates\bundles\release\classes.jar

The JAR file is created on the build procedure, In Android Studio GUI it's from Build->Make Project and from CMD line it's "gradlew build".

11
  • 3
    thou shall receive all my internets for this answer
    – m02ph3u5
    Commented Jun 2, 2015 at 13:45
  • 2
    Found it, in Build Variants, we have to choose Build Variant to be 'release'. But now the classes.jar is not present in the release folder! Commented Jun 18, 2015 at 19:34
  • 1
    @AparajithSairam how did you built your JAR, command line or gui ?
    – Avi Levin
    Commented Jun 21, 2015 at 21:21
  • 1
    @AparajithSairam, I found something in GUI but it relevant only for APK files builds. after selecting the relevant build variant press the green "play" icon. it will run a background assembly gradle command which will create the file. For a JAR file in CMD, you will have to run gradlew assembleDebug or Release or whatever flavor you have. After that the JAR would be available on the following location: your_app"\build\intermediates\bundles\"falvor"\classes.jar you can see all your assembly commands using "gradlew tasks"
    – Avi Levin
    Commented Jun 27, 2015 at 8:59
  • 1
    I upvoted another answer over a year ago. Screw that business. This is cake! Thanks!!
    – Kevin
    Commented Dec 15, 2015 at 23:42
31

Include the following into build.gradle:

android.libraryVariants.all { variant ->
    task("generate${variant.name}Javadoc", type: Javadoc) {
        description "Generates Javadoc for $variant.name."
        source = variant.javaCompile.source
        ext.androidJar = "${android.plugin.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"
        classpath = files(variant.javaCompile.classpath.files) + files(ext.androidJar)
    }

    task("javadoc${variant.name}", type: Jar) {
        classifier = "javadoc"
        description "Bundles Javadoc into a JAR file for $variant.name."
        from tasks["generate${variant.name}Javadoc"]

    }

    task("jar${variant.name}", type: Jar) {
        description "Bundles compiled .class files into a JAR file for $variant.name."
        dependsOn variant.javaCompile
        from variant.javaCompile.destinationDir
        exclude '**/R.class', '**/R$*.class', '**/R.html', '**/R.*.html'
    }
}

You can then execute gradle with: ./gradlew clean javadocRelease jarRelease which will build you your Jar and also a javadoc jar into the build/libs/ folder.

EDIT: With android gradle tools 1.10.+ getting the android SDK dir is different than before. You have to change the following (thanks Vishal!):

android.sdkDirectory 

instead of

android.plugin.sdkDirectory
3
  • Great answer, this worked perfectly for me. You can also add a gradle target in android studio to run the jarDebug task which will create the usable jar(I have tested this in an eclipse project and it also works fine).
    – Pellet
    Commented May 27, 2014 at 2:27
  • 8
    Why does the "new" Android build system make it this ugly :(. Commented Aug 1, 2014 at 4:56
  • Great solution to generate a JAR file! Is it possible to include the resources as well?
    – Gaëtan
    Commented Dec 4, 2014 at 16:07
13

I was able to export a jar file in Android Studio using this tutorial: https://www.youtube.com/watch?v=1i4I-Nph-Cw "How To Export Jar From Android Studio "

I updated my answer to include all the steps for exporting a JAR in Android Studio:

1) Create Android application project, go to app->build.gradle

2) Change the following in this file:

  • modify apply plugin: 'com.android.application' to apply plugin: 'com.android.library'

  • remove the following: applicationId, versionCode and versionName

  • Add the following code:

// Task to delete old jar
task deleteOldJar(type: Delete){
   delete 'release/AndroidPlugin2.jar'
}
// task to export contents as jar
task exportJar(type: Copy) {
    from ('build/intermediates/bundles/release/')
    into ('release/')
    include ('classes.jar')
    rename('classes.jar', 'AndroidPlugin2.jar')
}
exportJar.dependsOn(deleteOldJar, build)

3) Don't forget to click sync now in this file (top right or use sync button).

4) Click on Gradle tab (usually middle right) and scroll down to exportjar

5) Once you see the build successful message in the run window, using normal file explorer go to exported jar using the path: C:\Users\name\AndroidStudioProjects\ProjectName\app\release you should see in this directory your jar file.

Good Luck :)

2
  • 2
    Step 2 is critical. Nobody else mentions this. Thank you, this worked for me!
    – pookie
    Commented Jan 28, 2020 at 12:03
  • The path must have changed over several AndroidStudio versions. Instead of from ('build/intermediates/bundles/release/') this must read from ('build/intermediates/aar_main_jar/release/syncReleaseLibJars/'). Then the described steps work.
    – mmo
    Commented Sep 12 at 16:12
9

Here's yet another, slightly different answer with a few enhancements.

This code takes the .jar right out of the .aar. Personally, that gives me a bit more confidence that the bits being shipped via .jar are the same as the ones shipped via .aar. This also means that if you're using ProGuard, the output jar will be obfuscated as desired.

I also added a super "makeJar" task, that makes jars for all build variants.

task(makeJar) << {
    // Empty. We'll add dependencies for this task below
}

// Generate jar creation tasks for all build variants
android.libraryVariants.all { variant ->
    String taskName = "makeJar${variant.name.capitalize()}"

    // Create a jar by extracting it from the assembled .aar
    // This ensures that products distributed via .aar and .jar exactly the same bits
    task (taskName, type: Copy) {
        String archiveName = "${project.name}-${variant.name}"
        String outputDir = "${buildDir.getPath()}/outputs"

        dependsOn "assemble${variant.name.capitalize()}"
        from(zipTree("${outputDir}/aar/${archiveName}.aar"))
        into("${outputDir}/jar/")
        include('classes.jar')
        rename ('classes.jar', "${archiveName}-${variant.mergedFlavor.versionName}.jar")
    }

    makeJar.dependsOn tasks[taskName]
}

For the curious reader, I struggled to determine the correct variables and parameters that the com.android.library plugin uses to name .aar files. I finally found them in the Android Open Source Project here.

4

We can export a jar file for Android library project without resource files by Android studio. It is also requirement what I met recently.

1. Config your build.gradle file

    // Task to delete old jar

    task clearJar(type: Delete){
       delete 'release/lunademo.jar'
    }

    // task to export contents as jar
    task makeJar(type: Copy) {
       from ('build/intermediates/bundles/release/')
       into ('build/libs/')
       include ('classes.jar')
       rename('classes.jar', 'lunademo.jar')
    }
    makeJar.dependsOn(clearJar, build)

2. Run gradlew makeJar under your project root

You will see your libs under dir as build/libs/ if you are luckily.

============================================================

If you met issue as "Socket timeout exception" on command line as below,

enter image description here

You can follow this steps to open Gradle window in the right part and click "makeJar" on Android studio like this,

enter image description here

enter image description here

Then go to build/libs dir, you will see your jar file.

Hope that it is helpful for u.

Good Luck @.@

Luna

1
  • The path must have changed over several AndroidStudio versions. Instead of from ('build/intermediates/bundles/release/') this must read from ('build/intermediates/aar_main_jar/release/syncReleaseLibJars/'). Then the described steps work.
    – mmo
    Commented Sep 12 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.