android启动Service有两种方式,一种是startService,还有一种是bindService,关于startService的启动流程可以参照https://www.jianshu.com/p/fd31917c518a ,bindService的运行流程如下所示:

1、Activity.bindService-->ContextImpl.bindService-->ContextImpl.bindServiceCommon

ContextImpl.bindServiceCommon首先调用mPackageInfo.getServiceDispatcher获取IServiceConnection对象,IServiceConnection是个Binder类型,具体内容如下:

mPackageInfo.getServiceDispatcher中先创建了ServiceDispatcher,并传入bindService调用方的ServiceConnection,返回调用ServiceDispatcher.getIServiceConnection:

其中mIServiceConnection是在ServiceDispatcher中赋值的:

mIServiceConnection的实现类是InnerConnection:

InnerConnection是Binder Service端的存根,返回给Binder Client端进行跨进程调用的,在bindService的时候将InnerConnection对象传送给AMS,这样AMS就可以跨进程调用bindService调用方的ServiceConnection。这一点和ApplicationThread以及广播的IIntentReceiver如出一辙。
创建完IServiceConnection后就调用AMS的bindService并传入IServiceConnection对象。
2、AMS.bindService-->ActiveServices.bindServiceLocked-->ActiveServices.requestServiceBindingLocked
在bindServiceLocked函数中,判断是否是AUTO_CREATE,如果是,就调用bringUpServiceLocked启动Service并触发Service.onCreate,然后再requestServiceBindingLocked:

requestServiceBindingLocked会调用ApplicationThread.scheduleBindService
3、ApplicationThread.scheduleBindService-->ActivityThread.handleBindService

ActivityThread.handleBindService首先从mServices中取出要Binde的service(在第二步bindServiceLocked函数中会创建Service对象并保存),取到之后就调用s.onBind方法获取当前Service返回给远程bindService调用方的binder对象,最后调用AMS.plublishService,并将s.onBind传过去,该值最终会传给bindService的ServiceConnection.onServiceConnected中。
4、AMS.publishService-->ActiveServices.publishServiceLocked

ActiveServices.publishServiceLocked中调用了c.conn.connected,c.conn就是第一步中创建的InnerConnection对象,c.conn.connected会调用ServiceDispatcher.doConnected:

ServiceDispatcher.doConnected最终调用了ServiceConnection.onServiceConnectioned,并传入第三步中s.onBind的返回值。
5、bindService的调用以AMS.serviceDoneExecuting收尾。
在理解了startService和bindService的运行流程后,似乎对Service如何插件化还没任何思路。下面说下VirtualApk是如何实现的吧。
VitualApk在实现Service插件化的时候依然是采用的宿主占坑的方案,通过在宿主实现占坑的LocalService和RemoteService,

通过hook掉AMS启动Service相关的方法,如果发现是启动插件的Service,就将目标Service转化为宿主占坑的Service,再由宿主占坑Service实现代理转发,在宿主Service中反射加载插件Service的实例,并调用其对对应的方法,这里以LocalService为例,描述下整个流程:
1、Hook掉AMS的startService bindService等函数

hookSystemService会替换掉当前进程的AMS本地代理,实现了自己的ActivityManagerProxy

ActivityManagerProxy hook调用Service相关的方法,这里以startService为例:

startService中会调用startDelegateServiceForTarget:

其中wapperTargetIntent将启动插件Service的Intent转为启动宿主占坑Service:

2、LocalService的处理
第一步将启动插件Service的Intent转为了启动宿主占坑的LocalService,LocalService中会实现代理转发。LocalService.onStartCommand中有如下代码:

LocalService.onStartCommand首先反射创建插件Service对象,返回反射调用了其attach方法,最后调用了Service.onCreate,这样就完成了startService启动插件Service的插件化。
其他Service方法的插件化类似,可自行分析。
网友评论