将项目打包为aar:
1、manifest文件:去掉红框内容
2、Module的build.gradle文件中加上 apply plugin: 'com.android.library'
3、打包:
4、包位置:
在其他module中导入aar包
1、implementation和api的区别:
- api相当于之前的compile,用这种方式依赖的库,会参与编译打包过程。但是,如果第三方库以此方式依赖其他库,有可能会发生版本冲突。需要使用api("com.xxxxx.xxxxxx:xxxxx:1.0.0") { exclude group: 'com.android.support' }方式解决。
- implementation只能在模块内部使用,比如我在一个libiary中使用implementation依赖了gson库,然后我的主项目依赖了libiary,那么,我的主项目就无法访问gson库中的方法。如果需要提供外部访问,使用api即可。
2、compileOnly替代provided,都是只在编译时有效,不会参与打包
有多个library,只要确保有一个module中该依赖能参与到打包即可,其他的可以使用compileOnly,避免冲突。
这里可以选择将包放到maven仓库,也可以在本地进行导入。
本地导入:
1、通过放在libs下面进行导入
在需要导入的module的build.gradle中加入
repositories {
flatDir {
dirs 'libs'
}
}
implementation (name:'app-release',ext:'aar')
//implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')
2、通过file —> new module的方式
选择本地aar添加后可以看到
在需要的module中直接依赖:
implementation project(':app-release')
当项目存在多个module时,如果这些module都需要依赖同一些aar,可以建立一个底层的公共module(common),common中采用api的方式引入那些aar,那么其他module只需要依赖common就可以间接依赖到那些aar,方便同意操作。
common的build.gradle中
api project(':app-release')
其他module中
implementation project(':common')
maven仓库的方式
1、上传aar到maven仓库
我们在aar原项目的build.gradle中添加上传uploadArchives 的方法
apply plugin: 'maven'
uploadArchives {
repositories {
mavenDeployer {
repository(url: uri('../localMaven')) //定义本地maven仓库的地址
pom.version = 1.0
pom.artifactId = "aarText"
pom.groupId = "com.text.aarText"
pom.name = "testlibrary"
pom.packaging = 'aar'
}
}
}
apply plugin: "maven" 引入maven插件
repository(url: uri('../localMaven')) 定义maven仓库地址,一般是定义为远程仓库的地址,..表示上一层目录。
同步之后可以运行。运行后:
出现对应的目录,版本号,我们需要的aar文件。
2、引用maven仓库的aar
在需要引用的module的build.gradle文件中添加
repositories {
maven {
url '../../MyApplication2/localMaven'
}
}
dependencies {
implementation 'com.text.aarText:aarText:1.0'
}
url是仓库地址。
implementation 'groupId:artifactId:version'
同步之后,该module就可以使用aar中的东西。
如果全部module都要,则在project层级的build.gradle中添加maven地址
allprojects {
repositories {
google()
jcenter()
maven {
url '../../MyApplication2/localMaven'
}
}
}
然后在common中,注意是api
dependencies {
api 'com.text.aarText:testlibrary:1.0'
}