How to manually include external aar package using Gradle for Android
Asked Answered
C

28

529

I've been experimenting with the new android build system and I've run into a small issue. I've compiled my own aar package of ActionBarSherlock which I've called 'actionbarsherlock.aar'. What I'm trying to do is actually use this aar to build my final APK. If I include the whole ActionBarSherlock library as an android-library module to my main project using compile project (':actionbarsherlock') I'm able to build successfully without any problems.

But my problem is that I want to provide that dependency as a aar file package MANUALLY just if I would a JAR then I can't seem to figure out how to properly include it into my project. I've attempted to use the compile configuration but this doesn't seem to work. I keep on getting cannot find symbol during compile which tells me that the classes.jar from aar package isn't getting included in the classpath.

Does anyone know of the syntax to manually include an aar package as a file?

build.gradle

buildscript {

 repositories {
     mavenCentral()
  }
  dependencies {
    classpath 'com.android.tools.build:gradle:0.4'
  }
}
apply plugin: 'android'

repositories {
   mavenCentral()
}
dependencies {
    compile files('libs/actionbarsherlock.aar')
}

android {
    compileSdkVersion 15
    buildToolsVersion "17.0"
}

EDIT: So the answer is that it's not currently supported, here's the issue if you want to track it.

EDIT: Currently as this is still not supported directly the best alternative seems to be the proposed solution from @RanWakshlak

EDIT: Also simpler by using the syntax proposed by @VipulShah

Conceptualize answered 22/5, 2013 at 3:9 Comment(7)
Consider Vipul Shah's response: it finally worked for me, without local maven repository, as of Android Studio 0.5.8.Badderlocks
Take a look at my question and answer here https://mcmap.net/q/49384/-gradle-download-dependencies-lock-versions-and-update-dependencies-manuallyCanon
If you are using Gradle 3.0.0 or higher, this simple Gradle setup worked for me: #29081929Pillbox
it works for me : stackoverflow.com/a/67918749Neisa
Does this answer your question? Android Studio: Add jar as library?Bowra
See this answer of mine.Bowra
this is the simplest way i have seen. https://mcmap.net/q/49386/-how-to-import-aar-module-on-android-studio-4-2Lastminute
S
786

Please follow the steps below to get it working (I tested it up to Android Studio 2.2).

Let's say you have an .aar file in libs folder (e.g. cards.aar).

Then in app build.gradle specify following and click Sync Project with Gradle files.

Open Project level build.gradle and add flatDir {dirs("libs")} like below:

allprojects {
    repositories {
        jcenter()

        flatDir {
            dirs("libs")
        }
    }
}

Open app level build.gradle file and add .aar file:

dependencies {
    implementation(name:'cards', ext:'aar')
}

If you are using Kotlin and have a build.gradle.kts file:

dependencies {
    implementation(name = "cards", ext = "aar")
}

If everything goes well, you will see library entry is made in build -> exploded-aar.

Also note that if you are importing a .aar file from another project that has dependencies you'll need to include these in your build.gradle, too.

Sid answered 27/4, 2014 at 17:11 Comment(13)
@VipulShah where is the libs directory located?Lyricist
Maybe it should be advised to put modifications in the app module 'build.gradle' and not in the top folder 'build.gradle'.Illusionist
what do I do if I have two aar's: release and debug? eg. cards-debug.aar and cards-release.aar ?Kannan
found answer to my question above: instead of the compile dependency add two dependencies debugCompile(name:'cards-debug', ext:'aar') and releaseCompile(name:'cards-release', ext:'aar')Kannan
it's working but i think the First part is on settings build.gradle and the bottom part is on app build.gradleDebbi
flatDir is too slow on Android Studio 2.2.3 !!Autocorrelation
Don't be confused with the sample code. First block with allprojects {...} goes to the "project" level gradle file, and the second part with dependencies {...} should go to "app" level gradle file.Kirmess
Is there a recommended approach to distributing a library that contains an aar dependency like this? If I bundle my libraries aar, I'd like it to include this lib dependency such that my library's consumers do not need to download what they would consider a transitive dependency.Zygo
Great answer! Though I prefer the official way (import .jar or .aar package), I have found this method is the most reliable. The official method works with some aar packages, but not with others, but this always works. I use implementation fileTree(include: '*.aar', dir: 'libs') instead of doing it for every aar packages.Crandall
I believe the libs directory goes under the app directory. I got an error message Failed to resolve when I had libs in parallel with the app directory. But putting libs under app allowed me to compile.Dachi
Please update you answer: WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'. It will be removed at the end of 2018. For more information see: d.android.com/r/tools/update-dependency-configurations.htmlSelfgovernment
How would it looks in Kotlin DSL?Recently
Failed to resolve: :cards: Affected Modules: appAlameda
D
275
  1. Right click on your project and select "Open Module Settings".

Open module settings

  1. Click the "+" button in the top left corner of window to add a new module.

Add new module

  1. Select "Import .JAR or .AAR Package" and click the "Next" button.

Import AAR

  1. Find the AAR file using the ellipsis button "..." beside the "File name" field.

Find AAR file

  1. Keep the app's module selected and click on the Dependencies pane to add the new module as a dependency.

Dependencies pane

  1. Use the "+" button of the dependencies screen and select "Module dependency".

Add module dependency

  1. Select the module and click "OK".

Choose module

EDIT: Module dependency in screenshot 6 has been removed in Android Studio 4.1. As an alternative add the module dependency to the build.gradle.

dependencies {
    implementation project(':your_module')
}

EDIT: The user interface and the work flow have been changed a lot in Android Studio 4.2. The process to add a dependency is very well explained in an official documentation now: Adding dependencies with the Project Structure Dialog

Doykos answered 21/1, 2016 at 9:28 Comment(8)
Best Answer , keep in mind after that make Alt+B > clean and rebuild project . Android Studio why you are painful ! I wish to have NetBeans IDE as Android Developer PlatformRadiomicrometer
It's not the best idea to create a new module every time you just want to add some aar lib to your projectKirmess
I followed the steps and it works fine. But I am not able to access the .aar class method in my android class. Error error: cannot find symbol Could you please guide through this.Maller
Module Dependency option has been removed from the pop out menu in latest Android Studio (V4.1)Incur
As Module dependency has been removed in Android Studio 4.1 you have to add the module dependency to the build.gradle. I edited the post and added the new solution.Doykos
Any method that is based on GUI click this and GUI click that is not based on scientific method. This does not workConstituency
import .jar/.aar package is removed from add module in android studio 4.2 and moved to project structure dialog: developer.android.com/studio/projects/…Bans
@Bans very nice of you to point out that minute change. Other than that, this solution even does very little code line changes, and gets the work done, rather than the accepted solution.Bord
D
135

You can reference an aar file from a repository. A maven is an option, but there is a simpler solution: put the aar file in your libs directory and add a directory repository.

    repositories {
      mavenCentral()
      flatDir {
        dirs 'libs'
      }
    }

Then reference the library in the dependency section:

  dependencies {
        implementation 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar'
}

You can check out Min'an blog post for more info.

Duley answered 30/1, 2014 at 8:4 Comment(7)
This works great, and is better than the accepted/higher rated answers because it's simpler and I can include this in version control without adding the file to each developer's local maven repo (if I had to do that, why use Gradle in the first place?) Thanks!Turnip
@Turnip Probably be recommended to set up a repo server instead (for proprietary deps) so you don't have to put it on dev machines or in your project's lib folder. If you just have one dependency, throw it out into a maven structured Google code repository (as a temp repo)Upstate
The most important point to note in this answer is mentioning '@aar' at the end of the dependency.Encasement
I suppose this won't work anymore with latest gradle plugin: #60879099Ectoblast
This is the one and only answer that includes the simplest form, with all modern syntax, including implementation etc. This is copy-paste the solution. Lots of new upvotes incoming because Android Build Gradle Plugin 4.0.0 now throws an error instead of ignoring broken .aar pathsBenham
If you're using a settings.gradle file, be sure to use app/libs to reference your libs folder one level downHimes
I failed to make this work, always getting back some flavor of "Failed resolving dependency". The solution by @artiom using a local maven repo worked out great instead (and very quickly)Selinaselinda
H
79

before(default)

implementation fileTree(include: ['*.jar'], dir: 'libs')

just add '*.aar' in include array.

implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')

it works well on Android Studio 3.x.

if you want ignore some library? do like this.

implementation fileTree(include: ['*.jar', '*.aar'], exclude: 'test_aar*', dir: 'libs')
debugImplementation files('libs/test_aar-debug.aar')
releaseImplementation files('libs/test_aar-release.aar')
Haik answered 5/4, 2018 at 2:13 Comment(4)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Chinfest
Working fine, this is the way to go if the library is simple. But their is an issue here : You need to import all the library imported in your aar file to make it works. Import from the aar file are not propagated using this method.Genous
Or, even simpler: implementation fileTree(include: ['*.?ar'], dir: 'libs')Staves
@Staves Rather than simpler I would say shorter, and at the same time unspecific, theoretically.Ectoblast
C
59

The below approach works with Android studio v0.8.x:

  • Save the aar file under app module's libs folder (eg: <project>/<app>/libs/myaar.aar)

  • Add the below to build.gradle of your "app" module folder (not your project root build.gradle). Note the name in compile line, it is myaar@aar not myaar.aar.

     dependencies {
         compile 'package.name.of.your.aar:myaar@aar'
     }
    
     repositories{
         flatDir{
             dirs 'libs'
         }
     }
    
  • Click Tools -> Android -> Sync Project with Gradle Files

Camail answered 7/10, 2014 at 3:28 Comment(4)
Works perfect on AS 1.0Loria
In case someone needs it, if gradle works ok but you still can't see classes, restart Android Studio...Multiplechoice
This solution works great in AS2.2 - gradle is amazingly picky on syntax of AAR files it seems.Disposure
Please update or delete, compile is deprecated and there is also this issue: #60879099Ectoblast
T
57

Only One Time set-up & can add future libs without any code change


Add below line in app level build.gradle

implementation fileTree(dir: "libs", include: ["*.aar"])

Change Project structure from Android to Project.

Navigate to app->libs as below

enter image description here

Then paste "aar" in libs folder.

Click on File at top left of android studio and click "Sync Project with Gradle Files" as below.

enter image description here

That's it.

Tipi answered 13/11, 2020 at 10:39 Comment(1)
implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.aar")))) for kts filesDipper
A
41

With Android Studio 3.4 and Gradle 5 you can simply do it like this

dependencies {
    implementation files('libs/actionbarsherlock.aar')
}
Aerodrome answered 21/5, 2019 at 15:35 Comment(6)
This is the best answer. The dependency is explicit and very simple.Carvey
Agreed on this being the best answer. Instantly worked, was perfect for adding .aar dependencies to a React Native library.Neoterism
This throws an error starting with gradle plugin 4: #60879099Ectoblast
@Ectoblast Sorry, forgot to answer this. Works fine for me.Aerodrome
@Ectoblast You can't include aars for building an aar, this is not supported by Google's tooling, there's no way around that.Aerodrome
The only one that worksEggert
I
22

Currently referencing a local .aar file is not supported (as confirmed by Xavier Ducrochet)

What you can do instead is set up a local Maven repository (much more simple than it sounds) and reference the .aar from there.

I've written a blogpost detailing how to get it working here:

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

Inescutcheon answered 1/6, 2013 at 16:56 Comment(3)
I didn't manage to make it work when the artifact is a snapshot, any idea why ?Frigid
Did you get this working with Eclipse, or Android studio only? With eclipse, "gradle eclipse" adds the aar file to the classpath, but eclipse does not recognize classes within it.Enaenable
Check this question #20912165 if after following the tutorial your local .aar file is not found (on Gradle 1.9 or above)Ameba
S
21

I've just succeeded!

  1. Copy the mylib-0.1.aar file into the libs/ folder

  2. Add these lines to the bottom of build.gradle (should be app, not project):

    repositories {
       flatDir {
           dirs 'libs'
       }
    }
    dependencies {
        compile 'com.example.lib:mylib:0.1@aar'
    }
    
  3. So far so good. Here comes the most important point:

Gradle needs to access the network for dependencies unless offline mode is enabled.

Make sure that you have enabled Offline work via the checkbox in Project Structures/Gradle

-- OR --

Configure the proxy settings in order to access the network.

To configure the proxy settings you have to modify the project's gradle.properties file, configuring http and https separately as below:

systemProp.http.proxyHost=proxy.example.com
systemProp.http.proxyPort=8080
systemProp.http.proxyUser=user
systemProp.http.proxyPassword=pass
systemProp.http.nonProxyHosts=localhost
systemProp.http.auth.ntlm.domain=example <for NT auth>

systemProp.https.proxyHost=proxy.example.com
systemProp.https.proxyPort=8080
systemProp.https.proxyUser=user
systemProp.https.proxyPassword=pass
systemProp.https.nonProxyHosts=localhost
systemProp.https.auth.ntlm.domain=example <for NT auth>

Hope this works.

Stenography answered 2/3, 2015 at 14:32 Comment(1)
Please update or delete, compile is deprecated and there is also this issue: #60879099Ectoblast
O
21

There are 2 ways:

The first way

  1. Open your Android Studio and navigate to the Create New Module window by File -> New -> New Module

enter image description here

  1. Select the Import .JAR/.AAR Package item and click the Next button

  2. Add a dependency in the build.gradle file that belongs to your app module.

    dependencies {
        ...
        implementation project(path: ':your aar lib name')
    }

That's all.

The second way

  1. Create a folder in libs directory, such as aars.

  2. Put your aar lib into the aars folder.

  3. Add the code snippet

repositories {
    flatDir {
        dirs 'libs/aars'
    }
}

into your build.gradle file belongs to the app module.

  1. Add a dependency in the build.gradle file that belongs to your app module.
dependencies {
    ...
    implementation (name:'your aar lib name', ext:'aar')
}

That's all.

If you can read Chinese, you can check the blog 什么是AAR文件以及如何在Android开发中使用

Ornamental answered 23/3, 2018 at 8:8 Comment(4)
this answer was really helpful for meWite
When followed first way, classes inside aar file are not detected in main project, do we need to add any extra config?Southwards
Please update or delete, firs the answers are already posted and second "compile" is deprecated.Ectoblast
This method no longer works in current Android Studio (2021.2) - the "New Module" workflow does not have the option of importing a JAR/AAR package.Slighting
C
19

You can add multiple aar dependencies with just few lines of code.

Add local flatDir repository:

repositories {
    flatDir {
        dirs 'libs'
    }
} 

Add every aar in libs directory to compile dependency configuration:

fileTree(dir: 'libs', include: '**/*.aar')
        .each { File file ->
    dependencies.add("compile", [name: file.name.lastIndexOf('.').with { it != -1 ? file.name[0..<it] : file.name }, ext: 'aar'])
}
Canon answered 27/7, 2015 at 19:52 Comment(4)
This worked, But how can put a check , if the dependency is already added as a maven dependency then I dont want that aar file needs to be added, PS: Im using this to write a plugin which automatically adds my aar to the android project and adds dependency in build.gradleJuju
@Juju If you already have maven dependency then do not put corresponding aar to libs folder.Canon
Thanks for the response, As I mentioned, adding aar to libs is automated by a Android studio plugin which in developing, So I want to know whether the dependency which the plugin adds to the build.gradle file is already added previously.Juju
I do not have answer right now. I think it's better to create separate question.Canon
R
18

If you use Gradle Kotlin DSL, you need to add a file in your module directory.

For example: libs/someAndroidArchive.aar

After just write this in your module build.gradle.kts in the dependency block:

implementation(files("libs/someAndroidArchive.aar"))
Rheotropism answered 19/8, 2020 at 13:13 Comment(0)
B
16

To manually import AAR files with Android Studio Arctic Fox

Step 1. Open Project Structure
enter image description here

Step 2. Open Project Structure
enter image description here

Step 3. Enter file path
enter image description here

DONE!

Bilbe answered 9/9, 2021 at 14:57 Comment(0)
S
15

Unfortunately none of the solutions here worked for me (I get unresolved dependencies). What finally worked and is the easiest way IMHO is: Highlight the project name from Android Studio then File -> New Module -> Import JAR or AAR Package. Credit goes to the solution in this post

Slumgullion answered 8/6, 2015 at 15:44 Comment(1)
It should be noted that Android Studio is exceptionally vague in their import wizard. When they state "File Name" in one of the steps, what they are actually asking for is the file's path... Hopefully this message saves others from a headache.Disgruntle
F
12

UPDATE ANDROID STUDIO 3.4

  1. Go to File -> Project Structure

enter image description here

  1. Modules and click on +

enter image description here

  1. Select Import .aar Package

enter image description here

  1. Find the .aar route

enter image description here

  1. Finish and Apply, then verify if package is added

enter image description here

  1. Now in the app module, click on + and Module Dependency

enter image description here

  1. Check the library package and Ok

enter image description here

  1. Verify the added dependency

enter image description here

  1. And the project structure like this

enter image description here

Faustofaustus answered 3/7, 2019 at 16:15 Comment(1)
this is 17th answer I read that finally added dependency.. eehBibeau
D
7

I've also had this problem. This issue report: https://code.google.com/p/android/issues/detail?id=55863 seems to suggest that directly referencing the .AAR file is not supported.

Perhaps the alternative for now is to define the actionbarsherlock library as a Gradle library under the parent directory of your project and reference accordingly.

The syntax is defined here http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Referencing-a-Library

Dada answered 29/5, 2013 at 23:7 Comment(1)
Thank you for the reference to the issue. Yes I'm aware of how to make this work using Gradle Android Library but this option isn't really optimal for the project I'm working on but thx!Conceptualize
O
4

I found this workaround in the Android issue tracker: https://code.google.com/p/android/issues/detail?id=55863#c21

The trick (not a fix) is to isolating your .aar files into a subproject and adding your libs as artifacts:

configurations.create("default")
artifacts.add("default", file('somelib.jar'))
artifacts.add("default", file('someaar.aar'))

More info: Handling-transitive-dependencies-for-local-artifacts-jars-and-aar

Organdy answered 14/4, 2014 at 15:26 Comment(1)
That's right, and here is the example: in github.com/textileio/notes/commit/… , compile project(':mobile') in android/app/build.gradle , configurations.maybeCreate("default") in android/mobile/build.gradle , include ':mobile' in android/settings.gradleRum
A
4

In my case I have some depencies in my library and when I create an aar from it I failed, because of missed depencies, so my solution is to add all depencies from my lib with an arr file.

So my project level build.gradle looks so:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.2'
    }
}

allprojects {
    repositories {
        mavenCentral()
        //add it to be able to add depency to aar-files from libs folder in build.gradle(yoursAppModule)
        flatDir {
            dirs 'libs'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

build.gradle(modile app) so:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.sampleapp"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    //your project depencies
    ...
    //add lib via aar-depency
    compile(name: 'aarLibFileNameHere', ext: 'aar')
    //add all its internal depencies, as arr don't have it
    ...
}

and library build.gradle:

apply plugin: 'com.android.library'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    //here goes library projects dependencies, which you must include
    //in yours build.gradle(modile app) too
    ...
}
Aphrodisiac answered 26/7, 2016 at 18:12 Comment(0)
B
4

I tried all solution here but none is working, then I realise I made a mistake, I put the .aar in wrong folder, as you can see below, I thought I should put in root folder, so I created a libs folder there (1 in picture), but inside the app folder, there is already a libs, you should put in second libs, hope this help those who has same issue as mine:

enter image description here

Barnard answered 1/2, 2017 at 2:59 Comment(1)
Doesn't really matter, you can specify any path on the build.gradle file.Aerodrome
R
4

The standard way to import AAR file in an application is given in https://developer.android.com/studio/projects/android-library.html#AddDependency

Click File > New > New Module. Click Import .JAR/.AAR Package then click Next. Enter the location of the compiled AAR or JAR file then click Finish.

Please refer the link above for next steps.

Running answered 29/11, 2017 at 14:49 Comment(1)
You shouldn't depend on the GUI to add it but do it in build.gradleMay
P
3

There is 1 more way to do this.

Usually the .aar file is not supposed to be directly used like we use a .jar and hence the solutions mentioned above to mention it in libs folder and declaring in gradle can be avoided.

Step 1: Unpack the .aar file (You can do this by renaming its extension from ".aar" to ".zip")

Step 2: You will most probably find the .jar file in the folder after extraction. Copy this .jar file and paste it in your module/libs folder

Step 3: That's it, now sync your project and you should be able to access all classes/methods/ properties from that .jar . You don't need to mention about it's path/name/existence in any gradle file, this is because the gradle build system always looks out for files existing in libs folder while building the project

Pesky answered 11/2, 2021 at 14:24 Comment(0)
H
2

Just to simplify the answer

If .aar file is locally present then include
compile project(':project_directory') in dependencies of build.gradle of your project.

If .aar file present at remote then include compile 'com.*********.sdk:project_directory:0.0.1@aar' in dependencies of build.gradle of your project.

Harlene answered 9/10, 2017 at 6:34 Comment(0)
T
2

I just simply add these lines:-

in build.gradle

buildscript {
    repositories {
        flatDir {
            dirs 'libs'
        }
    }
}

and

implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')

after that click on file-> Sync Project with Gradle files

NOTE:- most important don't forget to import .aar file in libs folder

Tilden answered 26/10, 2022 at 5:6 Comment(0)
K
0

you can do something like this:

  1. Put your local libraries (with extension: .jar, .aar, ...) into 'libs' Folder (or another if you want).

  2. In build.gradle (app level), add this line into dependences

    implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')

Kellykellyann answered 29/11, 2018 at 2:37 Comment(0)
M
0

For me, this was an issue with how Android Studio environment was configured.

When I updated the File -> Project Structure -> JDK Location to a later Java version (jdk1.8.0_192.jdk - for me), everything started working.

Mcspadden answered 10/8, 2020 at 11:57 Comment(0)
C
0

This works for me. Windows11, Android Studio Hedgehog, Gradle-JDK: 17.0.7.

  1. Create new folder named mylibs in the root directory where app module is located.
  2. Create new folder named myaarname inside mylibs.
  3. Copy your myaar.aar into the mylibs/myaarname folder.
  4. Create new build.gradle file in mylibs/myaarname. And copy and paste code below into the file:
configurations.create("default")
artifacts.add("default", file('myaar.aar'))
  1. Add new line in the settings.gradle:
include(":mylibs:myaarname")
  1. Finally add aar into your module:
implementation(project.project(":mylibs:myaarname"))

PS: the names mylibs and myaarname are only for demonstration purposes. So, you can pick any suitable names for your needs.

Catercousin answered 20/3 at 5:39 Comment(0)
P
-1

In my case just work when i add "project" to compile:

repositories {
    mavenCentral()
    flatDir {
        dirs 'libs'
    }
}


dependencies {
   compile project('com.x.x:x:1.0.0')
}
Photon answered 20/4, 2018 at 20:21 Comment(0)
I
-1

Following solutions is simplest implementation of adding aar file in latest versions of Android and gradle :

implementation(files("libs/library_name.aar"))
Ildaile answered 4/4 at 8:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.