Android开发之项目模块化实践教程

前言

大家应该都知道,项目模块化是一个大命题,相信各团队都有其合理方案。本文不求涵盖各方面,仅从项目协同、开发调试、业务模块服务调用与通知三个方面简述一个可行方案。下面话不多说了,来一起看看详细的介绍吧。

项目协同

项目协同,也叫多项目协同,是对多个相关且有并行情况项目的管理模式,它是帮助实现项目与企业战略相结合的有效理论和工具[1]。本文的项目协同为Android主APP与其他业务模块的协同。

假设我们的APP目录如下,一个主app,多个modules。并假设我们的主app与各modules为多git repository。一个大APP多git repository管理是合理的。本文使用git repo[2]管理项目(可能有团队使用git submodule[3],在此不推荐,其坑会很多)。

MApp --独立git rep app modules   module1 --独立git rep   module2 --独立git rep   module3 --独立git rep   ...

使用git repo,团队早期可以不用玩一整套(git repo+gerrit),可以考虑只用repo去管理项目目录,成员提交代码还是继续走git提交。

项目开发与调试

Android模块化的主要目的是业务并行开发,减少编译时间,但又方便业务模块与主App的调试。本文介绍如下方案。

MApp app --application modules   module1     demo --application     lib --library     settings.gradle settings.gradle settings_debug.gradle local.properties 

MApp的settings.gradle文件:

 boolean moduleDebug() {  boolean ret = false  try {   Properties properties = new Properties()   File file = file('local.properties')   if (!file.exists()) {    return false   }   properties.load(file.newDataInputStream())   String debugStr = properties.getProperty("debug")   if (debugStr != null && debugStr.length() > 0) {    ret = debugStr.toBoolean()   }  } catch (Throwable throwable) {   throwable.printStackTrace()   ret = false  }  return ret }  include ':app' if (moduleDebug()) {  apply from: 'settings_debug.gradle' }

settings_debug.gradle文件:

//include 'module1'//project(':module1').projectDir = new File('modules/module1/lib')...其他业务模块 

当module1在需求开发阶段,完全不用考虑主APP,可以在Android Studio中以项目的方式打开。当module1需要和主APP跑流程时,我们只需要把MApp的local.properties的debug属性改为true,并在settings_debug.gradle中打开module1即可。

业务模块服务调用与通知

当APP模块化后,通过Intent(Context packageContext, Class<?> cls)方式去启动其他模块的Activity就不太合理了。模块化后,模块里的Activity或其他组件对其他业务模块最好透明。唤起Activity可以通过App Links[4]的方式,也就是我们常说的url router方式。App Links还可以玩deep link。Github上现在开源项目比如ARouter[5]就是App Link的应用。

当然,模块之间的通信,不局限于启动四大组件,还有服务调用与通知。这的服务不是Android系统的Service。举个服务通知的例子,在电商APP中,店铺详情页点收藏按钮,可能要通知其他模块,变更UI或数据。服务调用的例子,比如模块唤起登陆注册,登陆或注册成功后,做相应业务处理。

服务调用,大部分团队可能没涉及到。服务调用可以用IOC,反射等注册到服务注册中心。本文选一个取巧的方案。利用Applicatin.getSystemService方法,让Application作为ZoomKeep一样成为服务注册中心。只要各Serivce继承同一个Interface,相应模块间服务调用就不难了。

public class MApp extends Application {  @Override public Object getSystemService(String name) {  return super.getSystemService(name); }}

服务通知,稍简单,用广播,EventBus[6]或其他方式都可。本文推荐EventBus,但其有缺点,如Event多起来后,很难找全观察者和通知者之间的关系;一些简单Event对象无法复用,所以最好二次开发。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

参考

[1] 项目协同: http://www.baike.com/wiki/%E…

[2] git repo:https://gerrit.googlesource.com/git-repo/

[3] git submodule: https://git-scm.com/book/zh/v1/Git…

[4] App Links:https://developer.android.com/training/app-links/deep-linking.html

[5] ARouter:https://github.com/alibaba/ARouter

[6] EventBus:https://github.com/greenrobot/EventBus

可是,我却迈不开步伐,怎么也走不出那个圈……

Android开发之项目模块化实践教程

相关文章:

你感兴趣的文章:

标签云: