[android] How to manually include external aar package using new Gradle Android Build System

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

This question is related to android gradle android-gradle-plugin build.gradle

The answer is


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')


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"))

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


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


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


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


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.


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


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


  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


The below approach works with latest 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


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.


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.


Add below line in app level build.gradle

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

Change Project structure from Android to Project.

Navigaate 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.


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

dependencies {
    implementation files('libs/actionbarsherlock.aar')
}

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')
}

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.


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'])
}

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
    ...
}

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')

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.


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


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?????


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to gradle

Gradle - Move a folder from ABC to XYZ A failure occurred while executing com.android.build.gradle.internal.tasks Gradle: Could not determine java version from '11.0.2' Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 Failed to resolve: com.android.support:appcompat-v7:28.0 Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Examples related to android-gradle-plugin

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()' Android Material and appcompat Manifest merger failed Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries Invoke-customs are only supported starting with android 0 --min-api 26 error: resource android:attr/fontVariationSettings not found Exception : AAPT2 error: check logs for details Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)

Examples related to build.gradle

Android Material and appcompat Manifest merger failed Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve Android dependency has different version for the compile and runtime Setting up Gradle for api 26 (Android) What's the difference between implementation and compile in Gradle? More than one file was found with OS independent path 'META-INF/LICENSE' Android Studio - Failed to notify project evaluation listener error Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2 All com.android.support libraries must use the exact same version specification DELETE_FAILED_INTERNAL_ERROR Error while Installing APK