Please note, this is not a duplicate of this question from 10 years ago: Adding local .aar files to Gradle build using "flatDirs" is not working, because this once used to work, with the notice to avoid flatDirs
. I've faced this issue when migrating to AGP 8.5.1, with Gradle 8.9 - and now the previous approach apparently became obsolete. Therefore meanwhile the question is:
How to add *.aar
to an Android project without the flatDirs
repository?
This is how to add *.aar
files from the module's libs
directory into the module's class-path:
// define Task dependency
tasks.named("preBuild") {
dependsOn("extractAarLibraries")
}
tasks.register('extractAarLibraries') {
outputs.upToDateWhen {
// Report UP-TO-DATE, when there is a JAR for every AAR.
project.fileTree('libs').filter { it.name.endsWith('.aar') }.each { aar ->
if (! project.file("libs/${aar.name.replace('.aar', '.jar')}").exists()) {
return false
}
}
return true
}
doFirst {
project
.fileTree('libs')
.filter { it.name.endsWith('.aar') }
.each { aar ->
String libName = aar.name.replace('.aar', '')
String jarName = "${libName}.jar"
// When the JAR file does not exist in the destination.
if (! project.file("libs/${jarName}").exists()) {
// Extract AAR to temporary directory.
File outputDir = project.file("build/tmp/aarsToJars/${libName}/")
copy {
from zipTree(aar)
into outputDir
include '**/classes.jar'
eachFile {
if (it.getRelativePath().getFile(project.file(outputDir.path)).exists()) {
println "> ${outputDir}${File.separator}${it.path} exists."
it.exclude()
}
}
}
// Copy JAR into directory `libs`.
copy {
from outputDir
include '**/classes.jar'
into project.file('libs')
rename ('classes.jar', jarName)
}
}
}
}
doLast {
// Optional: delete the temporary directory.
// Please review what is being extracted first.
if (project.file('build/tmp/aarsToJars').exists()) {
delete project.fileTree('build/tmp/aarsToJars')
}
}
}
Interface FlatDirectoryArtifactRepository
even still exists.
Another option might be ExtractAarTransform
.