我们在开发中难免会遇到把现有的module变成库文件SDK的情况,aar包中不仅可以包含代码,也可以包含资源文件,是一种常用的库文件方式。打包的事项主要有以下几点:
- 在root project工程下的build.gradle文件中引入"com.kezong:fat-aar:1.3.3"
dependencies {
classpath 'com.android.tools.build:gradle:3.5.3'
classpath "com.kezong:fat-aar:1.3.3"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
引入这个库文件的作用,就是为了让我们打出的aar包中,自动包含module所依赖的其他三方库文件。
- 在需要打包的module中build.gradle文件中添加
plugins {
id 'com.android.library'
id 'com.kezong.fat-aar'
}
'com.android.library’表示这个module的产物是一个库文件;
'com.kezong.fat-aar’表示产物aar包会包含module依赖的库。
- 还是在module中build.gradle文件中添加
android.libraryVariants.all{ variant ->
variant.outputs.all{
def fileName = "demo-sdk-${defaultConfig.versionName}.${defaultConfig.versionCode}-${buildType.name}.aar"
outputFileName = fileName
}
}
这会根据versionName和versionCode去生成aar的名字,便于区分版本。
- 还是在module中build.gradle文件中,如果有引入第三方的库文件时,一定要用embed关键字引入
dependencies {
embed(name:"navi-service-sdk-6.0.1-debug",ext:'aar')
implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
当然,第三方库文件是需要放在lib文件夹下的
- 在Android Studio的右上角Gradle选项中,选择对应的Module -> Tasks -> build -> assemble,点击assemble就开始了aar包的构建,最后在工程目录对应的Module build目录下便可以找到我们需要的aar包。