【私人备忘录】Android P ActivityManagerService(三)Service启动和绑定

一、startService代码流程

Activity.java
startService(mBase.startService())
Context.java
startService()
ContextImpl.java
startService() → startServiceCommon(ActivityManager.getService().startService())
ActivityManagerService.java
startService(mServices.startServiceLocked())
ActiveServices.java
startServiceLocked() → startServiceInnerLocked() → bringUpServiceLocked(realStartServiceLocked(r, app, execInFg)) → realStartServiceLocked(app.thread.scheduleCreateService() && sendServiceArgsLocked(r.app.thread.scheduleServiceArgs()))
ActivityThread.java
1、scheduleCreateService(sendMessage(H.CREATE_SERVICE, s)) → handleMessage(case CREATE_SERVICE) → handleCreateService() → Service.onCreate
2、scheduleServiceArgs(sendMessage(H.SERVICE_ARGS, s)) → handleMessage(case SERVICE_ARGS) → handleServiceArgs(res = s.onStartCommand(data.args, data.flags, data.startId)) → Service.onStartCommand

备注:
handleCreateService()主要干了以下几件事:
1、通过类加载器创建Service的实例;service = packageInfo.getAppFactory().instantiateService(cl, data.info.name, data.intent);
2、创建ContextImpl对象;ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
3、创建Application对象并调用其onCreate,不过Application的创建过程只会有一次;Application app = packageInfo.makeApplication(false, mInstrumentation);
4、调用Service的attach方法建立ContextImpl和Application的关系,过程和activity类似;service.attach(context, this, data.info.name, data.token, app, ActivityManager.getService());
5、调用Service的onCreate方法并将Service对象存储到ActivityThread中的一个列表中;service.onCreate(); mServices.put(data.token, service);
 

二、bindService代码流程

ContextWrapper.java
bindService();Activity.java调用的是爷爷类ContextWrapper.java的bindService()
Context.java
bindService()
ContextImpl.java
bindService() → bindServiceCommon(ActivityManager.getService().bindService())
ActivityManagerService.java
bindService(mServices.bindServiceLocked())
ActiveServices.java
bindServiceLocked(bringUpServiceLocked() && requestServiceBindingLocked())
1、bringUpServiceLocked() → realStartServiceLocked(r, app, execInFg) → 接下去可以参考上面逻辑
2、requestServiceBindingLocked(r.app.thread.scheduleBindService())
ActivityThread.java
scheduleBindService(sendMessage(H.BIND_SERVICE, s)) → handleMessage(case BIND_SERVICE) → handleBindService(ActivityManager.getService().publishService())
ActivityManagerService.java
publishService(mServices.publishServiceLocked())
ActiveServices.java
publishServiceLocked(c.conn.connected(r.name, service, false))
LoadedApk.java
ServiceDispatcher.connected() → RunConnection(run()) → doConnected(mConnection.onServiceConnected(name, service)) → ServiceConnection.onServiceConnected()

备注:
1、c.conn是ConnectionRecord中的conn是IServiceConnection,是LoadedApk中ServiceDispatcher的InnerConnection实现的;private static class InnerConnection extends IServiceConnection.Stub
2、ServiceDispatcher.connected()中mActivityThread.post(new RunConnection(name, service, 0, dead));RunConnection经由ActivityThread中的H的post方法运行在主线程中,客户端ServiceConnection中的方法在主线程被回调。

你可能感兴趣的:(Android源码学习)