四大组件----Service 的启动和绑定过程源码图解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38089373/article/details/81000128

一.几个概念

Service 与 Activity 的启动有相似的地方,也有不同的地方。

  • 相似的地方在于 Service 的启动也涉及了几个概念, SystemsService ,C/S 架构,还有相应的几个对象,有的在 Activity 的启动过程 中就有介绍过,本篇就只对一些新增加的对象进行说明。
  • 不同的地方是 Service 有两种工作状态,一种是启动状态,一种是绑定状态,(当然还有启动+绑定状态)。不同的工作状态的就有不同的工作过程。

二.涉及的几个对象

(一)客户端( app 进程)

1.Context ,ContextImpl , ContextWapper

startService 和 bindService 是 Context 的方法,Activity 又继承自 ContextWapper ,而 ContextImpl 和 ContextWapper 继承 Context ,同时 ContextWapper 持有一个 ContextImpl 类型的对象。Service 的工作过程大部分是由 ContextImpl 来实现的。具体的继承关系如图:
Context继承关系.png

2.ServiceConnection ,ServiceDispatcher.InnerConnection

这两个是与 bindService 有关的,由于绑定服务可能是跨进程的,因此就需要一个 Binder 对象,InnerConnection 就是一个 Binder 对象,而 ServiceDispatcher 的主要作用就是连接 InnerConnection 和 ServiceConnection。

(二)服务端 (SystemService 进程)

1.ActiveServices

这是一个辅助 AMS 进程 Service 管理的类,Service 的启动,绑定和销毁都由这个类来完成。

三.大体流程

Service 大致流程.png
Service 大致流程 (2).png

四.启动具体流程

Service 启动流程1.png
Service 启动流程2.png

五.绑定具体流程

Service 绑定流程1.png

Service 绑定流程2.png

Service 绑定流程 3.png

参考资料

《Android 开发艺术探索》
startService启动过程分析
Service的启动过程
Service的绑定过程

猜你喜欢

转载自blog.csdn.net/m0_38089373/article/details/81000128