开发需求把项目中某一个模块功能封装一下给客户。就是开发一个Android libiary。
参考官方文档入门:
Android Libiary结构同Android项目一致,可以作为其他项目依赖。Android项目打包成apk,Android Library打包成arr
- 不同于jar包,ARR可以包含Android项目文件和清单文件;
- 可以包含C/C++库。
Android library 可以在如下场景使用
- 开发多个App使用同样的组件,比如含有相同的Activities、servicees,UI布局等;
- 比如一个App含有多中版本,免费办或者付费版,两个版本核心组件相同;
- 或者就是想让每个App Moudle都复用一些文件。
新建一个Android Library:
File-new-new Module,然后选择Android library,(官网提示可以选择java library,但是无法携带Android资源)。
将一个app module改为library module:
在module的build.gradule中,删除applicationId(包名),这个是app module特有的。
同时把顶部的
apply plugin: 'com.android.application'
修改为
apply plugin: 'com.android.library'
然后Sync Project with Gradle Files。
这时在项目结构里,这个module的图标就会变成library的图标。
还需要要删除applicaiton在manifest中的配置,去掉入口Activity。
如果想要打包arr,在project中选中library,然后build apk, 这里如果gradle的版本是3.5.1,是无法打包的,需要切换到高版本。
——升级了也没反应,文档这里可能有误。
build apk根本没反应,不知道我这里情况是不是个例,查了一下可以在gradle窗口给中,选择要打包的libiary,然后依次点击libiary下的Tasks-build-assemble,就可以打包arr了。
其实在标题栏下面的那个运行按钮,当项目时Android library时,点运行就是打包arr。
打包的时候需要一些报错的情况:
- 需要把switch替换为if。
- 需要处理Provider。
需要打包的模块使用了butterknife,需要在app的build文件中添加
apply plugin: 'com.jakewharton.butterknife'
并且需要把并且把所有R替换为R2,用Android studio的全局替换即可,包括初始化控件,数组,点击事件。
butterknife R2 编译后还需要报错 Resource id 为0,网上说需要把guild降级为3.5.3,但其实把项目build文件中把butterknife升级到最近版本(10.2.3)就可以了。
如果aar中引用了第三方依赖库,会报错ClassNotFind,这个问题比较麻烦,查到了一段话
The aar file doesn't contain the transitive dependencies and doesn't have a pom file which describes the dependencies used by the module.
It means that, if you are importing a aar file using a flatDir repository you have to specify the dependencies also in your project.
You should use a maven repository, private or public, to avoid the issue.
In this case, gradle downloads the dependencies using the pom file which will contains the dependencies list.
arr不包含依赖包,要么在引用arr的module中把需要库重新引用一遍,要么自己建一个marven库。