Android Studio: including AAR library from a library project

2.4k views Asked by At

In my Android Studio project I have two subprojects/modules: an Android application (App1) and an Android library project (LibraryProject1). App1 depends on LibraryProject1. So far so good.

However, LibraryProject1, in turn, needs to import an AAR library to work properly.

So my Configuration is as follows:
App1 includes LibraryProject1
LibraryProject1 includes dependency.aar

Now, to include dependecy.aar I use the method detailed here:

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

So basically in my build.gradle for LibraryProject1 I have:

repositories {
    flatDir {
        dirs 'libs'
    }
}

dependencies {
    compile (name:'dependency', ext:'aar') //my AAR dependency
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
}

Obviously, I put my dependency.aar file in the libs directory of LibraryProject1

However, this doesn't work. It seems that the repository added by LibraryProject1 is completely ignored and the local "libs" folder is not included as a repository, causing compilation to fail.

If I add the repository from the App1's build.gradle it works, but I don't want to do that, it's LibraryProject1 that needs the AAR file, not App1.

How can I do this??

2

There are 2 answers

2
Master_T On BEST ANSWER

Well, I found a way, but since it's very "hacky" I'll leave the question open, in case anyone comes up with a better, "proper" solution.

Basically the problem is that the flatDir repository is ignored at compilation time if included from LibraryProject1's build.gradle script, so what I do is I use App1's build.gradle to "inject" the flatDir repository in LibraryProject1. Something like this:

//App1 build.gradle
dependencies {
    //get libraryproject1 Project object
    Project p = project(':libraryproject1')

    //inject repository
    repositories{
        flatDir {
            dirs p.projectDir.absolutePath + '/libs'
        }
    }

    //include libraryproject1
    compile p
}

This effectively allows LibraryProject1 to include the external AAR library without having App1 include it. It's hacky but it works. Note that you still have to put:

//LibraryProject1 build.gradle
repositories {
    flatDir {
        dirs './libs'
    }
}

inside LibraryProject1's build.gradle otherwise, even if the project itself would compile fine, the IDE wouldn't recognize the types included in the AAR library. Note that the ./ in the path also seems to be important, without it the IDE still doesn't recognized the types.

1
user2476124 On

I faced to the same issue, and I figure out it by putting all libraries on that depends LibraryProject1 in LibraryProject1/libs as a .jar. I think that aar library cannot be linked to another aar library. Hope that help you, Best regards