140

We recently upgraded to Android Gradle Plugin 4.0.0-beta03. We are now seeing this error when building one of our library modules

$ ./gradlew library_module:assemble

Execution failed for task ':library_module:bundleDebugAar'.
> Direct local .aar file dependencies are not supported when building an AAR. 
The resulting AAR would be broken because the classes and Android resources from any local .aar 
file dependencies would not be packaged in the resulting AAR. Previous versions of the Android 
Gradle Plugin produce broken AARs in this case too (despite not throwing this error). The 
following direct local .aar file dependencies of the :library_module project caused this error: 
______.aar

I can see this was added to AGP a few months ago. But they provide no further info on why.

So.

  1. What was the problem? Any more info? I can't find a single bug report anywhere.
  2. How exactly can I fix this? Is this saying that I can't build one .aar that depends on other local .aars? What if this local aar was instead hosted on Maven Central or another remote repo? Why would that make a difference?
Sergey Glotov
  • 20,200
  • 11
  • 84
  • 98
tir38
  • 9,810
  • 10
  • 64
  • 107
  • @spollom@google.com some comment on this? – David May 05 '20 at 23:51
  • The whole problem is that this would resulted in a kind of fat AAR. Which is not any trivial task, but definitely something Google could do (as they have all the tools for it already working - they are able to merge any number of AARs into the APK), so they probably just do not want to (as the transitive dependencies are more proper way, in most of the cases). There is an existing community solution for this - see https://github.com/kezong/fat-aar-android - but be warned, it is not mature (e.g. does not support multi-flavour builds, or support for new AGP versions is coming too late, ...). – Jiří Křivánek Jun 08 '22 at 06:25

22 Answers22

145

I recently encountered the same issue, the fix was to remove the library from libs/ and import it using File -> New -> New Module -> Import .JAR/.AAR Package, then referencing it in the library module build.gradle file:

dependencies {
  implementation project(":imported_aar_module")
}

If you are on a newer Android Studio version (4.0.0+), this option is not available. Instead you have to do it manually.

  1. Create a new directory and put the following content into the build.gradle file withing the new directory:
configurations.maybeCreate("default")
artifacts.add("default", file('[nameOfTheAar].aar'))
  1. Place the aar into this new directoy. Next to the build.gradle file.
  2. Add the new created Gradle project to the settings.gradle file:
include(":pathToTheCreatedDirectory")
  1. Include the project in your library where you want to use the aar:
implementation project(":pathToTheCreatedDirectory", configuration = "default")
Paul Lefebvre
  • 6,253
  • 3
  • 28
  • 36
Sandi
  • 2,415
  • 1
  • 13
  • 11
  • 9
    With this solution we would suddendly need a few more modules. Sad that there are no more infos about this new warning, it's not really logical to me, our project works how it is. – David May 05 '20 at 13:55
  • 4
    Like nobody ever considered this scenario when making gradle – Yusuf X Sep 25 '20 at 03:59
  • 3
    I am getting this error "can't understand gradle setting. add path manually". anyone has an idea to solve this issue? – CanCoder Nov 11 '20 at 21:08
  • 9
    Just a heads up comment - I was looking for a solution where one AAR can contain another AAR. That is not the case with this answer. Second AAR is created successfully but it isn't bundled with the first one. – Viktor Brešan Dec 08 '20 at 15:16
  • I'm getting the same error as @leeCoder, any solution for this? – strok_777 Jun 04 '21 at 12:56
  • 30
    Import .JAR/.AAR Package is not available in android studio 4. – Sabrina Jun 14 '21 at 15:49
  • 7
    @Sabrina in this case you have to do it manually. Checkout this [github issue](https://github.com/brim-borium/spotify_sdk/issues/99#issuecomment-878910598) as an starter. – StefMa Aug 11 '21 at 13:42
  • 3
    The above solution work!. Go to ProjectLevel->RightClick->New->Module->Give Name to you module->Paste the .AAR file->Create a new build.gradle inside new module->Now follow the above steps shared by @Sandi. Your project structure should look like this https://github.com/brim-borium/spotify_sdk/issues/99#issuecomment-878910598. It works for the Android app too. – BAIJU SHARMA Aug 17 '21 at 03:27
  • Is there a way to include mutiple aar files in one directory with one build.gradle file? – yancaico Nov 03 '21 at 08:04
  • Can multiple aars be placed in the new directory and build.gradle? – yancaico Nov 15 '21 at 06:40
  • Yes it is possible. Exoplayer example: ```configurations.maybeCreate("default") artifacts.add("default", file("libs/exoplayer-core-2.10.1.aar")) artifacts.add("default", file("libs/exoplayer-r1.5.16.aar")) artifacts.add("default", file("libs/exoplayer-ui-2.10.1.aar"))``` – Michał Jabłoński Jan 20 '22 at 11:58
  • Am I missing something? I'm getting unresolved reference on my calls when I remove aar implementation from the build.gradle. I followed the steps in the github link above. – Snipe3000 Jan 24 '22 at 03:48
  • 18
    When I do this I get `Could not set unknown property 'configuration' for settings 'android' of type org.gradle.initialization.DefaultSettings.`, anyone else run into that? Gradle plugin 4.2.2. – Max Mar 05 '22 at 16:57
  • @Max getting the same error, did you find any solution for this? – KunalK Mar 16 '22 at 09:23
  • Lets say I got 3 different build variants they are debug, uat and production. Previously it was using flatdirs method in Project build gradle/ app build gradle but its deprecated. By using debugImplementation (name: 'otp-android-4.7.1-debug', ext: 'aar') uatImplementation (name: 'otp-android-4.7.1', ext: 'aar') releaseImplementation(name: 'otp-android-4.7.1', ext: 'aar') – SY MY Mar 22 '22 at 01:47
  • These method allow my debug build variant to use otp-android-4.7.1-debug in Library module > its libs folder. And uat and release build variant i will use another file (otp-android-4.7.1) in the same directory(Libarary module -> libs folder) Can anyone tell me how can I achieve this if i use artifacts.add("default", file("libs/exoplayer-ui-2.10.1.aar") ? – SY MY Mar 22 '22 at 01:48
  • Is that mean implementation project(":pathToTheCreatedDirectory", configuration = "default") the configuration is the build variant environment ? Then how can i point to different aars ? – SY MY Mar 22 '22 at 01:48
  • Lets say I got money1debug.aar, money2.aar and money3.aar in the include(":pathToTheCreatedDirectory") ? Is this way correct and can be supported please help!!! implementation project(":pathToTheCreatedDirectory/money1debug.aar", configuration = "debug") implementation project(":pathToTheCreatedDirectory/money2.aar", configuration = "uat") implementation project(":pathToTheCreatedDirectory/money3.aar", configuration = "release") My problem is ":pathToTheCreatedDirectory" then for different build variant i want to use different aar how to make it help please? – SY MY Mar 22 '22 at 01:49
  • 8
    `implementation project(":pathToTheCreatedDirectory", configuration = "default")` causes error `Could not set unknown property 'configuration'...` ____________________ `implementation project(":pathToTheCreatedDirectory")` works. – Eugene Babich Jun 30 '22 at 06:58
  • where need to include implementation project(":pathToTheCreatedDirectory", configuration = "default") – ravin kumar Feb 24 '23 at 12:18
  • I follow this answer, but face a new problem that I can't get like style, drawable, string included in the aar file in my project use java code link R.style.xxx R.drawable.xxx. – David Mar 24 '23 at 01:08
  • @Sandi My aar need some dependencie to work, how can I these dependencie on gradle? – Wellington Yogui Aug 29 '23 at 17:03
102

I want to call out @StefMa's comment on this question which was incredible simple and solved this issue for me, but it's buried among many other comments on this thread and is easily missed.

The 'correct' answer on this thread no longer works because it's not possible to import AARs in Android Studio anymore as referred to in that answer. But, the solution referred to in StefMa's comment linking to this GitHub post does, and it works perfectly.

Long story short - put your AAR into a separate module.

There's no need to muck around with creating lib directories, just follow these directions -

  1. Create a new directory in your project's root directory. The image below shows two of them - spotify-app-remote and spotify-auth, but one is sufficient. Within that, put your AAR in, and create a new build.gradle file.

    Folder structure

  2. Within the build.gradle file, add the following, replacing the aar filename with the name of your AAR file -

    configurations.maybeCreate("default")
    artifacts.add("default", file('spotify-app-remote-release-0.7.1.aar'))
    
  3. Add this to your settings.gradle file, substituting the name of the directory you created

    include ':spotify-app-remote'
    
  4. Include your new module in the module you wish to use the AAR. eg, if you want to use it within your app module, open app's build.gradle and add

    api project(':spotify-app-remote')
    

    within your dependencies { } block, obviously again substituting spotify-app-remote with whatever the name of your module is.

JJD
  • 50,076
  • 60
  • 203
  • 339
Jarrod Robins
  • 1,866
  • 2
  • 17
  • 23
  • 3
    Perfectly working. Thanks – Vamsi Dec 17 '21 at 07:20
  • 8
    This should be the accepted answer in 2021 and onward. This is really dumb to have to do this manually. So something tells me the developers of Android Studio aren't so stupid as to leave it this way , so probably in the next release of Android Studio, we'll all be back here trying to figure out yet another way of doing this. – deltamind106 Feb 08 '22 at 20:58
  • 2
    Is it possible to add multiple AARs to a to a single `library module` by adding multiple `artifacts.add` clauses? – Tash Pemhiwa Feb 17 '22 at 08:58
  • 3
    would it be possible to create example repo with this? I have an issue where gradle reports that "spotify" project cannot be found (I used my own name in my code) – Dusan Plavak Jul 07 '22 at 08:33
  • This worked, the other solutions above did not. – John T Jul 17 '22 at 06:41
  • 1
    I get "Internal error: Artifact type null not expected, only jar or aar are handled." when trying to use the module as a dependency for any other modules :/ – Brandon Dec 06 '22 at 07:30
  • This gives compilation errors due to manifest not found in the created directory. – hasan_shaikh Dec 22 '22 at 11:55
  • this worked perfect as the the OP stated, it must be created as "directory" and then the gradle should contain only 2 lines of code and add this to the settings.gradle, if you add as a "module" android will add extra lines/files to your gradle and might not work as expected – Javier Jan 10 '23 at 10:02
  • +1. The only downside of this solution is the fact you have to add it to the app/build.gradle, which makes putting the `aar` file in a library difficult. Ps. Joke's on us: this approach is still annoying AF in 2023. – DarkNeuron Jan 31 '23 at 16:12
  • @DarkNeuron Are you talking about when it is actually time to use the library in an app? Because I used the above way and while I could publish the library, my host application is not able to find the library's classes that belong to the aar. – Thomas Papapaschos Jul 05 '23 at 10:10
  • 1
    @ThomasPapapaschos I've gotten smarted since I posted my annoyance above: AAR's are not meant to be embedded, they are meant to be externally referenced libraries (think NPM). What I ended up doing what's putting the (closed source) AAR I required on "GitHub Packages", as a Maven repo. My application then references the AAR from there, and it works well. It was a bit of a hassle to set up though, and required reading a lot of docs, Maven docs included. Good luck is all I can say. – DarkNeuron Jul 06 '23 at 11:37
59

When building an Android library that depends on other Android libraries (i.e., aar files), you will get the following error message if you include the aar files as dependencies in the project:

Direct local .aar file dependencies are not supported when building an AAR. The resulting AAR would be broken because the classes and Android resources from any local .aar file dependencies would not be packaged in the resulting AAR. Previous versions of the Android Gradle Plugin produce broken AARs in this case too (despite not throwing this error).

As the above message states, when you build an Android library project, any aar it depends on is not packaged. If you built this way prior to AGP (Android Gradle Plugin) 4, you probably noticed that you had to include the aar dependencies on the project consuming your library.

You can compile your Android library project by specifying that the aar dependencies are compileOnly. See this for more info on when to use compileOnly.

So just add the following to your app build.gradle file:

compileOnly files('libs/some-library.aar')

Note that if you do this you will have to include the aar dependencies on the application project that consumes your library.

Alternatively, you can create a module that imports your aar dependency as @Sandi mentioned in the answer above.

Another way is to publish your aar dependencies to a maven repository and then add them to your library project like this:

implementation 'mylibrarygroup:mylibraryartifact:version-x.y.z@aar'
Luis
  • 3,451
  • 1
  • 27
  • 41
  • Your answer really help me out. Thanks. – yancaico Oct 10 '20 at 03:33
  • 7
    Not sure how this answer ever helped anyone. Google states: "You can't use the compileOnly configuration with AAR dependencies." in their docs: https://developer.android.com/studio/build/dependencies – DarkNeuron Mar 30 '21 at 08:30
  • 1
    @DarkNeuron that's because the OP's use case is different: you have a library project that compiles to an aar which also depends on other aars. So for this case, compileOnly works with the caveats noted in my answer (i.e., you have to include the aar dependencies that are compile only in the project consuming the library) – Luis Mar 30 '21 at 23:33
  • 1
    What? No no, my use case was exactly the same: Was building a library that used an AAR. I posted the above because it did NOT work. Everything compiled, but the library was missing from the final bundle. Which left me confused until I saw that note by Google. In any case I solved my aar problem by extracting the jar file contained within. Which might not work for everyone. – DarkNeuron Apr 01 '21 at 11:17
  • @DarkNeuron which library was missing? You need to assemble the aar... the final aar won't have your aar dependencies packaged. – Luis Apr 01 '21 at 19:28
  • Same problem with me: compileOnly allows to assembleRelease but the apk crashes because it actually misses the dependencies from the aar files... – Żabojad Feb 07 '22 at 14:26
  • 2
    @Żabojad then you didn't understand the above answer. You have to include the dependencies. – Luis Feb 08 '22 at 05:01
  • 1
    How to include the aar dependencies on the application project that consumes your library ? how to publish your aar dependencies to a maven repository ? @Luis – Ahmed Eid Sep 22 '22 at 09:00
  • One thousand thanks. That! was my problem. – Oscar Parra Mar 17 '23 at 18:54
12

In my experience, when Gradle Plugin version is 4.2.2+ and Gradle version is 7.1+, as in @Luis's answer 'compileOnly' works.

compileOnly files('libs/your_library_name.aar')

It didn't work when the Gradle versions were lower.

  • 13
    With this it compiles but later on in the app it crash when I try to call this lib – murt Oct 18 '21 at 07:49
  • @murt Do you have log of the crash? – Vishudh Sasidharan Oct 19 '21 at 00:51
  • 1
    Yes it compiles indeed, but the aar is then not loaded at runtime and the app crashes. – Żabojad Feb 07 '22 at 16:28
  • 2
    Yes, this is only half the answer. @Luis answer add the important addition; "Note that if you do this you will have to include the aar dependencies on the application project that consumes your library." See Simon answer for how to do that. – BenClark Feb 28 '22 at 13:10
9

Getting same error when use this code.

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

Replace your code with following.

Open the top level ‘build.gradle’ file and add.

repositories {
        flatDir {
            dirs('/src/main/libs')
        }
    }

Then in your project’s build.gradle add the following.

api(name:'aar_module_name', ext:'aar')
user2659769
  • 91
  • 2
  • 2
9

I had the same issue, in the sense I wanted to encapsulate a library dependency into a module. However this library dependency had a bunch of aars and creating separate module each of them is just clutter, and can't even find that option in the new studio.

To resolve it I published the aar-s into my local maven, before starting the build process.

So my encapsulating module's build.gradle looked like this:

plugins {
  id 'com.android.library'
  id 'kotlin-android'
  id 'maven-publish'
}
//..
parent.allprojects { // for some reason simply repositories didn't work
  repositories {
    mavenLocal() 
  }
}
//...
publishing {
  publications {
    barOne(MavenPublication) {
        groupId 'foo-aar-dependency'
        artifactId 'bar1'
        version '1.0'
        artifact("$libsDirName/bar1.aar")
    }
    barTwo(MavenPublication) {
        groupId 'foo-aar-dependency'
        artifactId 'bar2'
        version '1.0'
        artifact("$libsDirName/bar2.aar")
    }
    barThree(MavenPublication) {
        groupId 'foo-aar-dependency'
        artifactId 'bar3'
        version '1.0'
        artifact("$libsDirName/bar3.aar")
    }
    // and so on...
  }
}

// add the publication before the build even starts
// used ./gradlew mymodule:assemble --dry-run to find where to put it
afterEvaluate {
  tasks.clean.dependsOn("publishToMavenLocal")
  tasks.preBuild.dependsOn("publishToMavenLocal")
}

dependencies {
  implementation "foo-aar-dependency:bar1:1.0"
  implementation "foo-aar-dependency:bar2:1.0"
  implementation "foo-aar-dependency:bar3:1.0"
  // and so on
  // also I had to make sure to add the aar's transitive dependencies as implementation below
}

Note: When I sync for the first time the dependencies are not found, but as soon as any clean/assemble is called the dependencies are published prior so it runs as it needs.

Note2: most of this can be moved into a separate file to not clutter your build.gradle

Note3: If you actually want to publish your module as a library this solution is not for you.

Note4: This also works on CI if you run clean then your next task.

Gergely Hegedus
  • 482
  • 3
  • 9
  • 2
    this is the true answer! Maven is recommended over unsupported AAR dependencies, and I have been looking for a way to use my local AARs/artifacts from mavenLocal. Bravo and thank you @Gergely Hegedus! – Jeff Aug 11 '22 at 15:26
  • This solution work perfectly, covering encapsulation if you're planning to publish library. You saved my week !! – Son Tieu Nov 15 '22 at 09:30
  • @SonTieu did you publish your library to mavenCentral with local AAR dependencies? Does this solution work for mavenCentral or only mavenLocal? – Kuvonchbek Yakubov Nov 15 '22 at 16:52
  • @KuvonchbekYakubov i tried to use my own aar, so this solution worked in my case with mavenLocal. I haven't tried to publish to mavenCentral though. – Son Tieu Nov 18 '22 at 02:28
  • @Gergely Hegedus If my aar have dependencies, how would you declare it in this case ? i want something like specifying where my aar's pom is, along with my aar artifact. – Son Tieu Nov 18 '22 at 02:30
  • @SonTieu Ideally the aar you are using should have a pom file, you attach that to the maven publication. If not, you create that pom file yourself. gradle link: https://docs.gradle.org/current/dsl/org.gradle.api.publish.maven.MavenPom.html#org.gradle.api.publish.maven.MavenPom:withXml(org.gradle.api.Action) – Gergely Hegedus Nov 19 '22 at 07:18
7

There are some changes now, You need to add your AAR or JAR as a dependency

1.) First, Navigate to File > Project Structure [Reference Image 1]1

2.) Then go to Dependencies > Declared Dependencies tab, click and select JAR/AAR Dependency in the dropdown [Reference Image 2]2

3.)In the Add Jar/Aar Dependency dialog, first enter the path to your .aar or .jar file, then select the configuration to which the dependency applies. If the library should be available to all configurations, select the "implementation" configuration. [Reference Image 3]3

4.) Click OK then Apply > OK.

You are good to go.

Boken
  • 4,825
  • 10
  • 32
  • 42
Simon
  • 103
  • 1
  • 1
  • It works! But the file structure is different from the Sandi's answer. – BobTheCat Jan 04 '22 at 06:35
  • 2
    I tried this for a library module and it did not work. This is what the OP is about. I am quite sure this approach works perfectly for an app module. – Hong Apr 20 '22 at 14:25
  • I did this, and it worked until I renamed the project directory. Tried to redo it, not working. – John T Jul 16 '22 at 00:41
4

For those who prefer to use as a regular dependency (or an item on your Gradle's version catalog):

  1. Create a folder eg. spotifyAppRemote at the same level of app folder
  2. Add the desired .aar file at the root of spotifyAppRemote folder
  3. Create a settings.gradle.kts file at the root of spotifyAppRemote folder. This file will be empty, it just needs to be there for the composite builds. See: docs
  4. Create a build.gradle.kts file at the root of spotifyAppRemote folder:
plugins {
    base //allows IDE clean to trigger clean on this module too
}

configurations.maybeCreate("default")
artifacts.add("default", file("spotify-app-remote-release-0.7.2.aar"))

//Change group to whatever you want. Here I'm using the package from the aar that I'm importing from
group = "com.spotify.android"
version = "0.7.2"
  1. Next add Gradle files to this folder to allow this module to build itself. You can do it manually or add the following snippet at the root of settings.gradle.kts (!! the project root, not the empty one created above)
/* Optional - automatically sync gradle files for included build */
rootDir.run {
    listOf(
        "gradle.properties",
        "gradlew.bat",
        "gradlew",
        "gradle/wrapper/gradle-wrapper.jar",
        "gradle/wrapper/gradle-wrapper.properties"
    ).map { path ->
        resolve(path)
            .copyTo(
                target = rootDir.resolve("spotifyAppRemote").resolve(path),
                overwrite = true
            )
    }
}
  1. Now you can go ahead and add this folder as a module at the settings.gradle.kts on your project root. The same where may add the snippet above:
rootProject.name = "Your project name"
include(":app")
includeBuild("spotifyAppRemote")
  1. Sync and build your project.
  2. Now your included build will be available for your as a regular dependency with the defined group and version. To use this dependency:
dependencies {
    // group:moduleName:version
    implementation("com.spotify.android:spotifyAppRemote:0.7.2")
} 

Thanks other members for the solution.

Source code on github: https://github.com/rsicarelli/SpotifySdkCompositeBuild

rsicarelli
  • 1,013
  • 1
  • 11
  • 28
  • Please provide the solution for groovy (settings.gradle) – Palak Aug 04 '22 at 05:50
  • 2
    This solution works properly (the library builds and the module classes are available) but if I export the library as .aar into another Android project, the module code is missing. Inspecting the library .aar file, it does not embed the dependency module. – Akamaccio Oct 21 '22 at 11:12
  • @matmacci were you able to fix it? i have same problem – Lukáš Šálek Oct 21 '22 at 13:06
  • 1
    @Lukᚊálek I've opened a [new question](https://stackoverflow.com/questions/74151295/embed-aar-and-jar-files-in-a-library), but noone has given any answer yet. It's incredible that Google does not provide any clear information about that. – Akamaccio Oct 24 '22 at 08:47
  • I published a library to maven, this solution works for the compile error. However, the .aar library won't be included in the published library – Kuvonchbek Yakubov Nov 12 '22 at 19:22
  • 1
    You literally saved my day! Very precise, detailed explanation on your Github page. Thank you ! – Mert Kılıç Jul 11 '23 at 15:49
4

Patch the problematic 3rd party dependency's build.gradle file. Under their dependencies { } section, they had a line like this:

implementation fileTree(dir: 'libs', include: ['*.jar','*.aar']) //Load all aars and jars from libs folder

My patch changes that line to:

implementation(name: 'the-name-of-the-aar', ext: 'aar')

In my project's build.gradle, under allprojects { repositories { }, added:

flatDir { dirs "$rootDir/../node_modules/the-third-party-dependency/android/src/main/libs" } 

Where the AAR file lives

It was tested with reactnative >= 0.69.x

Leandro Ariel
  • 727
  • 8
  • 5
4

I faced a similar problem:

Task: add .aar SDK inside another SDK

Solution:

  1. We have to create new Android Library Module inside our library (right click on our library name -> module -> Android library )

  2. Delete all files inside it

  3. Insert our .arr inside this module

  4. Create build.gradle file inside module and put there:

    configurations.maybeCreate("default")
    artifacts.add("default", file('your_arr_name.aar'))
    
  5. Add to your library build.gradle inside dependencies block next:

    implementation project(':your_library:your_arr_module')
    
  6. Now rebuild project and everything should work fine

Antoine
  • 1,393
  • 4
  • 20
  • 26
  • It's the only answer that worked for me. Additionally, I had to manually move the created module folder inside my library's folder. I also noticed that root-level `settings.gradle` was appended with `include ':your_library:your_arr_module'`, which is important to include if you're linking a React Native library. [I had an issue with `react-native-spotify-remote` library which failed on the release Gradle build, so I had to fork it & apply this fix] – Daniel Jan 25 '23 at 14:53
  • I follow this step, and solve my problem.but face a new problem that I can't get style, string, drawable and other resources in my java code like R.style.xxx R.string.xxx – David Mar 24 '23 at 00:50
2

If you want to bundle a local .aar within your library and use that library in another project, you could take a look at "fat aars" https://github.com/kezong/fat-aar-android

Lukas Lechner
  • 7,881
  • 7
  • 40
  • 53
  • 1
    Be warned: The FAT AAR somehow works. But it is NOT mature enough. It only supports some AGP features. Notably, it does not support multi-flavour builds. Also, it is a community effort, so it is always behind the head (support for new AGPs is coming easily 1 year later). It is a real shame that Google is too lazy to add and maintain the FAT AAR feature themselves. They already have all the required functionality (they are able to merge any number of AARs when producing the APK). – Jiří Křivánek Jun 08 '22 at 06:15
2

Rather than creating a new module for the .aar. A much simpler approach is to have the app module add the .aar file as a dependency. The library module could just have a compileOnly dependency on the .aar file.

I usually set it up in the following way,

In the root directory, I have a folder global-libs. Copy the .aar library file here.

app-module -

implementation(files("../global-libs/some-lib.aar"))

library-module -

compileOnly(files("../global-libs/some-lib.aar"))

This way the .aar is bundled in the final apk, and the build also succeeds without any warning.

Gabriel
  • 307
  • 2
  • 8
1

EDIT : if the AAR does not contain android resources or native code, this could help you.

If you want this local resource directly linked to an "app" or "sdk" module (no compileOnly)

=> Use a jar.

  • Rename the .aar to .zip
  • Extract it
  • Use the classes.jar inside

That's it.

michgauz
  • 214
  • 2
  • 10
0

It is bug in Android Studio 4.0.+.However, there is a solution.

First, project/build.gradle:

allprojects {
   repositories {
        google()
        jcenter()
        mavenCentral()
        flatDir {dirs "../MoudleA/aars,../MoudleB/aars,../MoudleC/libs".split(",")
        }
    }
}

Second, Moudle/build.gradle:

// MoudleA/build.gradle

repositories {
    flatDir {
        dirs 'aars'
    }
}

dependencies {
    api fileTree(dir: 'libs', include: ['*.jar'])
    //api fileTree(dir: 'aars', include: ['*.aar'])
    // aar
    new File('MoudleA/aars').traverse(
            nameFilter: ~/.*\.aar/
    ) { file ->
        def name = file.getName().replace('.aar', '')
        api(name: name, ext: 'aar')
    }
}

// MoudleB/build.gradle

repositories {
    flatDir {
        dirs 'aars'
    }
}

dependencies {
    api fileTree(dir: 'libs', include: ['*.jar'])
    //fullApi fileTree(dir: 'aars/full', include: ['*.aar'])
    //liteApi fileTree(dir: 'aars/lite', include: ['*.aar'])
    // aar
    new File('MoudleB/aars/full').traverse(
            nameFilter: ~/.*\.aar/
    ) { file ->
        def name = file.getName().replace('.aar', '')
        fullApi(name: 'full/' + name, ext: 'aar')
    }
    new File('MoudleB/aars/lite').traverse(
            nameFilter: ~/.*\.aar/
    ) { file ->
        def name = file.getName().replace('.aar', '')
        liteApi(name: 'lite/' + name, ext: 'aar')
    }

}

// MoudleC/build.gradle

repositories {
    flatDir {
        dirs 'libs'
    }
}

dependencies {
    //api fileTree(dir: 'libs', include: ['*.jar','*.aar'])
    api fileTree(dir: 'libs', include: ['*.jar'])
    // aar
    new File('MoudleC/libs').traverse(
            nameFilter: ~/.*\.aar/
    ) { file ->
        def name = file.getName().replace('.aar', '')
        api(name: name, ext: 'aar')
    }
}

It works for me,You can also try.

daozi
  • 99
  • 1
0

You can upload the AARs to an Artifactory, and consume them.

DoronK
  • 4,837
  • 2
  • 32
  • 37
0

In my case, I realised that I have created libs folder at wrong place then recreated folder in main folder and implementation fileTree(include: ['*.aar'], dir: 'libs') worked.

Amin Pinjari
  • 2,129
  • 3
  • 25
  • 53
0

Adapt aar dependency to maven repo standards and depend on it.

Lets connect the dependency in build.gradle

repositories {
    maven { url "$project.projectDir/libs" }
}

dependencies {
    api "my-library-group:my-library-module:my-library-version"
}

Replace you libs/myLibrary.arr file with next files:

libs/my-library-group/my-library-module/my-library-version/my-library-module-my-library-version.aar
libs/my-library-group/my-library-module/my-library-version/my-library-module-my-library-version.pom
libs/my-library-group/my-library-module/maven-metadata-local.xml

Where my-library-module-my-library-version.aar is the original aar file

Content of my-library-module-my-library-version.pom

<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>my-library-group</groupId>
  <artifactId>my-library-module</artifactId>
  <version>my-library-version</version>
  <packaging>aar</packaging>
</project>

Content of maven-metadata-local.xml

<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>my-library-group</groupId>
  <artifactId>my-library-module</artifactId>
  <versioning>
    <latest>my-library-version</latest>
    <release>my-library-version</release>
    <versions>
      <version>my-library-version</version>
    </versions>
    <lastUpdated>20211130111015</lastUpdated>
  </versioning>
</metadata>

Feel free to replace my-library-group, my-library-module, my-library-version with any value you like

Link182
  • 733
  • 6
  • 15
  • I have tried but getting error. Can u please post your full build.gradle files or post the github link for convenience. @Link182 – Nadeem Iqbal Aug 15 '22 at 14:20
0

Good news for everyone. It seems that we can finally include AARs without subprojects again. I was able to accomplish it using the implementation files directive as follows in the dependencies { } block:

implementation files('ssi.aar')

so001
  • 418
  • 4
  • 16
  • 1
    I already have this directive in my project but I still have this problem. – James Mar 10 '23 at 05:30
  • where did you include the ssi.aar file? in libs folder? – Moustafa EL-Saghier Mar 14 '23 at 20:37
  • @MoustafaEL-Saghier you can put the file anywhere. it doesn't have to be the libs folder. – so001 Mar 15 '23 at 21:11
  • When I don't use `libs/` before `ssi.aar`, it doesn't find the aar: `Null extracted folder for artifact: ResolvedArtifact(componentIdentifier=ssi.aar, variant=local file, variantName=null, artifactFile=.../moduleName/ssi.aar, isTestFixturesArtifact=false, extractedFolder=null, publishedLintJar=null, dependencyType=ANDROID, isWrappedModule=false, buildMapping={__current_build__=/projectName})`. And when I use, I still get the same error as the question – Dr.jacky Apr 06 '23 at 13:22
0

My use case was for creating a Flutter Plugin but the solution was still the same as Link182's. I did find an implementation that I used as an example on Github

However, I had to use explicit version (X.X.X) rather than + to get it to work after creating maven directories, .pom, and manifest files: api(group: 'com.example.group', name:'exampleArtifact', version: '1.0.0')

-1

I also hit this issue when I increase my Android plugin version to 4.0.1, and it turns to error, tried some solutions but none of them are actually doable in our project.
Since we are using product flavours, and different flavours are using different local aar file, we simply can not just using api(name: "xxx", ext: 'aar') since those aar files are located in different flatDir.
For now I have to roll back to previous gradle plugin version.
will edit this answer if I figure something out

Kael luo
  • 79
  • 1
  • 5
-1

Much lazier way to do this in build.gradle.kts files is to use a fileTree combined with flatDir repository.

repositories {
  flatDir {
    dir("$rootDir/libraries")
  }
}

dependencies {
   fileTree("$rootDir/libraries").forEach { file ->
        implementation(group = "", name = file.name.removeSuffix(".aar"), ext = "aar")
    }
}

This way when you add or remove deps to the folder they are automatically configured

Chris.Jenkins
  • 13,051
  • 4
  • 60
  • 61
-4

for me works this solution: put into dependences in build.gradle:app file this string:

api fileTree(dir: 'libs', include: ['*.aar'])
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
gyparr
  • 15
  • 1