- 在项目引用过多的library时我们可以将library打包成aar包来引用。通常的我们会把一些公共jar包只配置到base包下,其他library只要引用base就能引用到该jar包。在配置aar包时,我们也会想只配置aar在base,这时引用base的其他module都会报错不能解析此aar,有这个问题的可以跳到末尾。
- 首先是生成aar包与引用aar包
- library只要编译过了在build/outputs目录下就会有对用的包,这里我们使用release的包
- 将library放在对应module的libs包下,名字可以修改
- build.gradle文件添加repositories
-
buildTypes { debug { minifyEnabled false debuggable true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } repositories { flatDir { dirs 'libs' } }
- 添加dependencies
-
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile(name: 'image-selector-1.0', ext: 'aar')//aar引用 compile project(':vlayout') compile 'com.crittercism.dexmaker:dexmaker:1.4' compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.android.support:appcompat-v7:21.0.0' compile 'com.android.support:support-annotations:21.0.0' compile 'com.android.support:cardview-v7:23.1.1' }
- 这样就可以在该module中引用aar包了
- 这种配置方式会存在一个小问题,当把这个aar像jar包一样只配置在base包下,供多个模块使用时,其他library会报错不能解析image-selector-1.0.aar
- 解决方法有三种
- 第一种就是使用as来导入aar,当成一个library来引用。方式为new module
然后选择自己的arr包,就能生成一个类似的library。在base里面应用就行了。问题是解决了,但是还是有一个目录在哪,总感觉不自在。不行还得想办法 - 第二种方式就简单了,arr还是在放在base包下的libs中,dependencies的写法也是一样只需要把repositories的代码修改一下移到真个project的build.gradle中.
- 第三种方式在比较高的gradle plugin版本3.0.0下可以直接使用fileTree来依赖aar
implementation fileTree(include: ['*.jar','*.aar'], dir: 'libs')
dirs'../你放aar包的library名称/libs' 就是路径名,build 的脚本使用 groovy 语言编写“..”代表回退,因为所有的library在同一级目录。gradle编译每个library时读到 '../你放aar包的library名称/libs' 回回退上一级目录在进入放入aar包的目录/libs中找到aar包。把这个repositories的路径配置到整个项目的build.gradle中就不需要每个library中都去配置了。这样就可以偷懒了 嘻嘻~