I need to publish my android library (aar) using Gradle to Maven local repo.
But the publication script needs to also generate the Javadocs, while ONLY including Public and Protected methods and classes.
Can't seem to find any information online, especially about the Javadocs part...
Help, I never published a library before.
Ok, after much research I found a solution, so I'm going to share it here if anyone will need this. (I don't want you to be frustrated like I was).
1) Create an android library as a new module inside your project.
2) Inside the build gradle of your library place this code:
plugins {
id 'com.android.library'
id 'maven-publish'
}
android {
nothing special here...
}
This is the code for creating the Javadocs(still inside build.gradle):
task androidJavadocs(type: Javadoc){
source = android.sourceSets.main.java.srcDirs
classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
android.libraryVariants.all{ variant->
if (variant.name == 'release'){
owner.classpath += variant.javaCompileProvider.get().classpath
}
}
// excluding a specific class from being documented
exclude '**/NameOfClassToExclude.java'
title = null
options{
doclet = "com.google.doclava.Doclava"
docletpath = [file("libs/doclava-1.0.6.jar")]
noTimestamp = false
// show only Protected & Public
memberLevel = JavadocMemberLevel.PROTECTED
}
}
task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs){
archiveClassifier.set('javadoc')
from androidJavadocs.destinationDir
}
task androidSourcesJar(type: Jar){
archiveClassifier.set('sources')
from android.sourceSets.main.java.srcDirs
}
This is to publish the library to MavenLocal(still inside build.gradle):
afterEvaluate {
publishing{
publications{
release(MavenPublication){
groupId = "com.example.mylibrary"
artifactId = "mycoollibrary"
version = "1.0"
// Applies the component for the release build variant
from components.release
// Adds javadocs and sources as separate jars.
artifact androidSourcesJar
artifact androidJavadocsJar
}
}
}
}
Your default dependencies block:
dependencies {
your dependencies...
}
3) Now you can download the doclava doclet:
Extract the zip, copy the doclava-1.0.6.jar and paste it into your LibraryName/libs folder (can be found using the project view).
You only need doclava if you want to be able to use #hide.
With this annotation, you can exclude specific methods from your Javadocs.
4) Build and publish your library:
Find the gradle tab at the top right side of android studio, or find it from the toolbar View->Tool Windows->Gradle.
Now find your library -> tasks -> publishing -> publishReleasePublicationToMavenLocal.
5) To consume the library from another project:
Go to the settings.gradle file (of the consuming project) and add MavenLocal() as the first repository in the the dependencyResolutionManagement block.
And inside the module build gradle add your library as a dependency:
dependencies{
implementation 'com.example.mylibrary:mycoollibrary:1.0'
}
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.
What was the problem? Any more info? I can't find a single bug report anywhere.
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?
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.
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'))
Place the aar into this new directoy. Next to the build.gradle file.
Add the new created Gradle project to the settings.gradle file:
include(":pathToTheCreatedDirectory")
Include the project in your library where you want to use the aar:
implementation project(":pathToTheCreatedDirectory", configuration = "default")
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 -
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.
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'))
Add this to your settings.gradle file, substituting the name of the directory you created
include ':spotify-app-remote'
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.
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'
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.
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')
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]
2.) Then go to Dependencies > Declared Dependencies tab, click and select JAR/AAR Dependency in the dropdown
[Reference Image 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]
4.) Click OK then Apply > OK.
You are good to go.
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.
For those who prefer to use as a regular dependency (or an item on your Gradle's version catalog):
Create a folder eg. spotifyAppRemote at the same level of app folder
Add the desired .aar file at the root of spotifyAppRemote folder
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
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"
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
)
}
}
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")
Sync and build your project.
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
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
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.
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
I faced a similar problem:
Task: add .aar SDK inside another SDK
Solution:
We have to create new Android Library Module inside our library (right click on our library name -> module -> Android library )
Delete all files inside it
Insert our .arr inside this module
Create build.gradle file inside module and put there:
configurations.maybeCreate("default")
artifacts.add("default", file('your_arr_name.aar'))
Add to your library build.gradle inside dependencies block next:
implementation project(':your_library:your_arr_module')
Now rebuild project and everything should work fine
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.
You can upload the AARs to an Artifactory, and consume them.
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.
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
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')
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
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
for me works this solution:
put into dependences in build.gradle:app file this string:
api fileTree(dir: 'libs', include: ['*.aar'])
I have a library module that I want to include as an AAR dependency into a sample app:
:my-library
:sample-app
So in sample/build.gradle, I do the following:
repositories {
flatDir {
dirs "../my-library/build/outputs/aar"
}
}
// I have different flavors that specify whether to use the source or binary (aar) dependency
flavorDimensions "SOURCE_OR_BINARY"
productFlavors {
source { }
binary { }
}
dependencies {
sourceImplementation project(':my-library')
binaryImplementation(name: 'my-library-release', ext: 'aar') // <-- this line fails with error
}
tasks.whenTaskAdded { task ->
def taskName = task.name.toLowerCase()
if (taskName.toLowerCase().contains("binary")) {
// Prepare libs as binaries
task.dependsOn ('my-library:assembleRelease')
}
}
This works fine with ./gradlew on the command line, but Android Studio reports a Failed to resolve: :my-library-release: during gradle sync. If I do a ./gradlew assemble on the command line, then sync Android Studio, the the AS Gradle sync succeeds.
The issue has to do with the timing of binaryImplementation(name: 'my-library-release', ext: 'aar'). When Gradle Sync is executed, the aar does not exist yet because it has yet to be built.
Is there a better way to do this that will avoid the Failed to resolve Android Studio Gradle sync error?
You need to add this to your app main build.gradle.
repositories {
/...
/...
flatDir {
dirs 'libs'
}
}
Lets say if you .aar file in the lib folder,then you could do something like this.
implementation files('libs/assembleRelease.aar')
You can try import with this way,
File -> New Module -> Import .Jar/.AAR package
I suggest that you use a local maven repository rather that flatDir. Dependencies which come from FileCollection and/or flatDir are not as full-featured as those coming from a "real" repository (eg maven/ivy)
Eg:
repositories {
maven {
url file("${rootProject.projectDir}/mavenRepo")
}
}
dependencies {
binaryImplementation "my-group:my-artifact:1.0#aar"
...
}
You'd then store the artifact using the maven repository directory layout. Eg:
rootProject/mavenRepo/my-group/my-artifact/1.0/my-artifact-1.0.aar
The answer can be found here - expose a configuration with that AAR, and consume that configuration downstream
https://docs.gradle.org/current/userguide/cross_project_publications.html
I have a multi-module gradle project that looks like this:
Parent
|--server
|--application (android module)
+--common
The server tests have a dependency on the common module tests. For this, I added
testCompile files(project(':common').sourceSets.test.output.classesDi
compileTestJava.dependsOn tasks.getByPath(':common:testClasses')
and it worked great. Unfortunately, when I tried to do the same thing for the application module that also has a dependency on the common module tests, it wouldn't work. It fails with:
Build file 'application\build.gradle' line: 103
A problem occurred evaluating project ':application'.
Could not find property 'sourceSets' on project ':common'
After googling a bit I also tried
project.evaluationDependsOn(':common')
testCompile files(project(':common').sourceSets.test.output.classesDir)
But fails with another exception:
Project application: Only Jar-type local dependencies are supported. Cannot handle: common\build\classes\test
Any ideas on how to fix this?
There's a couple of approaches solving the problem of importing test classes in this article. https://softnoise.wordpress.com/2014/09/07/gradle-sub-project-test-dependencies-in-multi-project-builds/ The one I used is:
code in shared module:
task jarTest (type: Jar) {
from sourceSets.test.output
classifier = 'test'
}
configurations {
testOutput
}
artifacts {
testOutput jarTest
}
code in module depending on the shared module:
dependencies{
testCompile project(path: ':common', configuration: 'testOutput')
}
And there seems to be a plugin for it as well! https://plugins.gradle.org/plugin/com.github.hauner.jarTest/1.0
Following the approach from sakis, this should be the configuration you need to get the tests available from another project in the Android platform (done for debug variant).
Shared module:
task jarTests(type: Jar, dependsOn: "assembleDebugUnitTest") {
classifier = 'tests'
from "$buildDir/intermediates/classes/test/debug"
}
configurations {
unitTestArtifact
}
artifacts {
unitTestArtifact jarTests
}
Your module:
dependencies {
testCompile project(path: ":libName", configuration: "unitTestArtifact")
}
The solution mentioned by droidpl for Android + Kotlin looks like this:
task jarTests(type: Jar, dependsOn: "assembleDebugUnitTest") {
getArchiveClassifier().set('tests')
from "$buildDir/tmp/kotlin-classes/debugUnitTest"
}
configurations {
unitTestArtifact
}
artifacts {
unitTestArtifact jarTests
}
Gradle for project that is going to use dependencies:
testImplementation project(path: ':shared', configuration: 'unitTestArtifact')
I know it's kinda an old question but the solution mentioned in the following blog solves the problem very nicely and is not a sort of hack or a temporary workaround:
Shared test sources in Gradle multi-module project
It works something like this:
// in your module's build.gradle file that needs tests from another module
dependencies {
testCompile project(path: ':path.to.project', configuration: 'test')
}
Also you should note that in the very last paragraph he mentioned that you need to enable Create separate module per source set in IntelliJ settings. But it works fine without using that option too. Probably due to changes in the recent IntelliJ versions.
EDIT: IntelliJ recognizes this fine as of 2020.x versions.
I think you could use gradles java test fixtures. This will automatically create a testFixtures source set, in which you can write your test that you want to reuse.
Test fixtures are configured so that:
they can see the main source set classes
test sources can see the test fixtures classes
For example, if you have some class in common module:
public class CommonDto {
private final Long id;
private final String name;
// getters/setters and other methods ...
}
Then in the common module, you could write into src/testFixtures/java following utils:
public class Utils {
private static final CommonDto A = new CommonDto(1, "A");
private static final CommonDto B = new CommonDto(2, "B");
public static CommonDto a() { return A; }
public static CommonDto b() { return B; }
}
Then in you other modules you could add this to reuse Utils class
dependencies {
// other dependencies ...
testImplementation(testFixtures(project(":common")))
}
All of this is better explained in the documentation that I provided initially. There are some nuances that you need to take into account until you create this not to leak test classes into production.