Android 为模块设置库依赖

Android setup library dependencies for module

背景:

我有一个 Android 项目,我想在其中将特定功能重构为一个 module。我的应用程序结构如下所示:

MyApp
|--app
|----build.gradle
|--myNewModule
|----build.gradle
|build.gradle (MyApp Project)
|settings.gradle

任务:

在项目中,我有一些只在 myNewModule 中需要的依赖项和整个项目都需要的一些依赖项,例如okHttpClient.

建议:

目前,我的 gradle 文件如下所示:

build.gradle(MyApp 项目)

定义变量以在整个项目中设置相同的库版本。

...
ext {

    butterknifeVersion = "7.0.1"
    daggerVersion = "2.6"
    moshiVersion = "1.1.0"
    okhttpVersion = "3.4.1"
    ...
}
...

build.gradle(我的新模块) 定义此模块所需的依赖项

...
dependencies {

    compile ("com.squareup.retrofit2:converter-simplexml:$retrofitVersion") {
        exclude group: 'stax', module: 'stax-api'
        exclude group: 'stax', module: 'stax'
        exclude group: 'xpp3', module: 'xpp3'
    }
    compile "com.squareup.okhttp3:okhttp-urlconnection:$project.okHttpVersion"
    compile "com.squareup.okhttp3:okhttp:$project.okHttpVersion"
    compile "com.squareup.okhttp3:logging-interceptor:$project.okHttpVersion"
    ....
} 
...

build.gradle(应用程序) 定义其他依赖项,是否可以与 MyNewModule 中的依赖项重叠?

...
dependencies {
    compile "com.jakewharton:butterknife:$project.butterknifeVersion"
    compile "com.jakewharton.timber:timber:$project.timberVersion"
    compile "com.jakewharton.threetenabp:threetenabp:$project.threetenabpVersion"

    compile "com.squareup.okhttp3:okhttp-urlconnection:$project.okHttpVersion"
    compile "com.squareup.okhttp3:okhttp:$project.okHttpVersion"
    compile "com.squareup.okhttp3:logging-interceptor:$project.okHttpVersion"
    ...
}
...

题目:

build.gradle(MyApp 项目)

在此处添加整个项目的所有依赖项?

...
dependencies {
    compile "com.jakewharton:butterknife:$project.butterknifeVersion"
    compile "com.jakewharton.timber:timber:$project.timberVersion"
    compile "com.jakewharton.threetenabp:threetenabp:$project.threetenabpVersion"

    compile "com.squareup.okhttp3:okhttp-urlconnection:$project.okHttpVersion"
    compile "com.squareup.okhttp3:okhttp:$project.okHttpVersion"
    compile "com.squareup.okhttp3:logging-interceptor:$project.okHttpVersion"
    ...
}
...

我只想遵循良好的设计模式,不增加项目的 dexcount,因为它使用了很多库并且接近多 dex,我想避免这种情况。

编辑:我更改了第二个问题的措辞,因为它具有误导性。 我只是想在两个模块中添加一些相同的依赖项,因为我可能会从 myNewModule 中创建一个单独的库,然后它仍然需要例如一个okHttpClient,不能再依赖主项目中的依赖了。

If I have a dependency for the same library in different modules, will Android recognize it as one dependency or will it double the dexcount for the apk?

Gradle 自动处理。
如果您在库和使用该库的模块中添加相同的依赖项,gradle 将添加它们 仅一次 .

Would this be a good way to define dependencies? In my case, the myNewModule will contain dependencies, which are only needed in it, but also dependencies, that are needed in the app module.

我认为不是。
您的库应包含仅需要的依赖项
没有理由还包括将由将使用它的模块使用的依赖项。

Or else, could I have put common dependencies directly into the build.gradle file from the Project?

问题不是很清楚
每个模块都应该有其依赖项,但您可以按照问题中描述的相同方式集中它们。