一尘不染

Android Gradle将外部库和嵌套的外部库添加到项目

java

如何将外部库和嵌套的外部库添加到android项目?


我的项目结构(不允许更改)

  • 应用/
    • App1 /
    • build.gradle
    • settings.gradle
    • 图书馆/
    • 图书馆1 /
      • 建立等级
      • settings.gradle
    • 图书馆2 /
      • 建立等级
      • settings.gradle
    • 图书馆3 /
      • 建立等级
      • settings.gradle
    • 图书馆4 /
      • 建立等级
      • settings.gradle

应用1

App1 / build.gradle

buildscript {
    ...
}

apply plugin: 'android'

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    compile project(':..:libraries:library1')
    compile project(':..:libraries:library2')
    compile project(':..:libraries:library3')
    compile project(':..:libraries:library4')
}

android {
    ...
}

App1不直接依赖library3library4,但是,如果我不在build.gradle文件和settings.gradle文件的依赖项中包括它们,它将抱怨。所以,我让他们加入只是为了阻止它抱怨。

App1 / settings.gradle

include ':'
include '..:libraries:library1'
include '..:libraries:library2'
include '..:libraries:library3'
include '..:libraries:library4'

图书馆1

library1 / build.gradle

buildscript {
    ...
}

apply plugin: 'android-library'

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    compile project(':..:library3')
    compile project(':..:library4')
}

android {
    ...
}

library1 / settings.gradle

include ':'
include '..:library3'
include '..:library4'

图书馆2..4

library2..4 / build.gradle

buildscript {
    ...
}

apply plugin: 'android-library'

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
}

android {
    ...
}

library2..4 / settings.gradle

include ':'

当试图gradlew clean buildApp1我得到以下错误:

FAILURE: Build failed with an exception.

* Where:
Build file '/home/user/projects/branches/branch1/Apps/libraries/library1/build.gradle' line: 15

* What went wrong:
A problem occurred evaluating project ':..:library:library1'.
> Project with path ':..:library3' could not be found in project ':..:library:library1'.

线15 compile project(':..:library3')library1/build.gradle的文件。

如何将外部库和嵌套的外部库添加到android项目?


阅读 192

收藏
2020-12-03

共1个答案

一尘不染

在顶级settings.gradle(App1 / settings.gradle)文件中,对每个库执行类似的操作

include ':library1'   
include ':library2'   
include ':library3'   
include ':library4'

project(':library1').projectDir = new File(rootProject.projectDir, '../libraries/library1')
project(':library2').projectDir = new File(rootProject.projectDir, '../libraries/library2')
project(':library3').projectDir = new File(rootProject.projectDir, '../libraries/library3')
project(':library4').projectDir = new File(rootProject.projectDir, '../libraries/library4')

删除其他settings.gradle文件,您不需要它们

然后在每个构建脚本中,您只需要使用

compile project (':library1')
compile project (':library2')
etc....

如上所述,只需在根项目(App1)中使用单个settings.gradle文件。

然后从您的App1文件夹运行gradlew clean :library1:build以验证library1是否正确构建。

至于有关App1抱怨缺少库3和4的问题,您确定应用程序中没有直接引用这些库的代码,或者在编译library1时找不到这些库。分别构建每个库以验证它们都可以正常构建。

2020-12-03