问题描述
创建项目后,会生成第一个module:app。
module:app 依赖了 module:baseapp
module:baseapp 依赖了 module:c
如果没有特殊依赖,此时编译是不会产生任何问题的。
module:baseapp 依赖 baseapp/libs/android_gif_drawable.aar。按常规处理,在baseapp的build.gradle文件中应该添加
//【步骤1】
dependencies {
compile(name: ‘android_gif_drawable’, ext: ‘aar’)
}
//【步骤2】
repositories {
flatDir {
dirs ‘libs’
}
}
此时编译,发现报错,提示:app的build.gradle中木有找到android_gif_drawable.aar
Error:A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_prodDebugApkCopy'.
> Could not find :android_gif_drawable:.
Required by:
project :app > project :baseapp
问题原因
原因1:flatDir.dirs 配置了什么?
//【步骤1】
dependencies {
compile(name: ‘android_gif_drawable’, ext: ‘aar’)
}
在 baseapp/build.gradle
中,我们声明了 ‘android_gif_drawable’为 ‘aar’格式的依赖,这种依赖关系和library Module是同级的
然而,我们在引用 library Module时会类似 compile project(':jni')
这样子借用project()
函数,来告知gradle对应依赖的路径位置
那么aar方式的依赖,如何告知gradle具体的资源路径呢?这就是步骤2
//【步骤2】
repositories {
flatDir {
dirs ‘libs’
}
}
这是一个相对路径,注意我们是配置在baseapp/build.gradle
中的,那么 baseapp在gradle编译时就知道“哦~ ‘android_gif_drawable’是一个aar,它的路径是在我当前目录下的libs中,也就是 baseapp/libs”
这也解释了,baseapp独立打包为aar是可以编译通过的原因
原因2:Application要找到所有依赖的依赖
aar 本身就是一种library Module,直接作用在 apply plugin:’com.android.application’中的
也就是说,app需要知道baseapp的所有依赖的位置,如果是远程依赖就拉下来远程依赖的代码,如果是本地依赖就要找到本地依赖的位置
所以,出现了这样一种逻辑:
app在集成baseapp时发现,
“哦~ android_gif_drawable是一个aar,它在那里呢?
flatDir.dirs指向的路径
也是在我当前目录下的libs中,也就是 app/libs”
然后发现,“诶,怎么没有?” 于是报错
解决途径
途径1:全工程下的路径穷举
在Project 下的 build.gradle 中的 repositories 中添加相应的引用如下:
allprojects {
repositories {
jcenter()
flatDir {
// 由于Library module中引用了 gif 库的 aar,在多 module 的情况下,
// 其他的module编译会报错,所以需要在所有工程的repositories
// 下把Library module中的libs目录添加到依赖关系中
dirs 'libs'
dirs project(':baseapp').file('libs') //借助 project()函数的位置查找
//dirs '../baseapp/libs' // 直接指明路径,注意前边的../, 要先回到根目录去查找别的module
}
}
}
途径2:所有依赖 Module baseapp 的 Module/build.gradle中 都添加
repositories {
flatDir {
dirs 'xxx/libs' // Module A的libs的目录地址
}
}
把所有的 Module 都添加上 Module A 的 libs 目录的相对地址。