Failed to resolve local AAR built from local sourc

2020-04-05 06:54发布

问题:

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?

回答1:

You can try import with this way,

File -> New Module -> Import .Jar/.AAR package



回答2:

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


回答3:

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-library: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


回答4:

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