创建工程
- New -> Module -> Library
- 在gradle文件头添加 apply plugin: ‘com.android.library’
打包模块
在库工程的 build.gradle 中最下方加入如下配置示例:
// 删除已存在的 Jar 包
task deleteOldJar(type: Delete) {
delete 'build/libs/analytics.jar'
}
// 创建 Jar 包
task makeJar(type: org.gradle.api.tasks.bundling.Jar) {
// 指定生成的jar名
baseName 'analytics'
// 指定 cn/soulapp/android/lib 包名目录
from('build/intermediates/classes/debug/cn/soulapp/android/lib/')
// jar包的目录结构(文件处于cn/soulapp/android/lib目录下)
// 生成的jar包没有包名
into('cn/soulapp/android/lib/')
//去掉不需要打包的目录和文件
exclude('BuildConfig.class', 'R.class')
//去掉R$开头的文件
exclude { it.name.startsWith('R$'); }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
执行命令
./gradlew makeJar
- 1
导入依赖
在 app 宿主工程的 build.gradle dependencies {} 中加入:
implementation fileTree(dir: 'libs', include: ['*.jar'])
- 1
结语
导入完成,您可以将自己的公共模块已 jar 报的形势依赖,达成解耦及复用效果。