contextImpl.java
bindService -> bindServiceCommon
private boolean bindServiceCommon(Intent service, ServiceConnection conn, long flags,
String instanceName, Handler handler, Executor executor, UserHandle user) {
// Keep this in sync with DevicePolicyManager.bindDeviceAdminServiceAsUser and
// ActivityManagerLocal.bindSdkSandboxService
IServiceConnection sd;
if (conn == null) {
throw new IllegalArgumentException("connection is null");
}
if (handler != null && executor != null) {
throw new IllegalArgumentException("Handler and Executor both supplied");
}
//后续获取connection执行onConnect回调就是从sd当中获取到的
if (mPackageInfo != null) {
if (executor != null) {
sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), executor, flags);
} else {
sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
}
} else {
throw new RuntimeException("Not supported in system context");
}
validateServiceIntent(service);
try {
IBinder token = getActivityToken();
if (token == null && (flags&BIND_AUTO_CREATE) == 0 && mPackageInfo != null
&& mPackageInfo.getApplicationInfo().targetSdkVersion
< android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
flags |= BIND_WAIVE_PRIORITY;
}
service.prepareToLeaveProcess(this);
//bind调用AMS
int res = ActivityManager.getService().bindServiceInstance(
mMainThread.getApplicationThread(), getActivityToken(), service,
service.resolveTypeIfNeeded(getContentResolver()),
sd, flags, instanceName, getOpPackageName(), user.getIdentifier());
if (res < 0) {
throw new SecurityException(
"Not allowed to bind to service " + service);
}
return res != 0;
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
ActivityManagerService.java
bindServiceInstance: 调用ActivityService的bindServiceLocked方法
ActivityService.java
和Service相关的具体操作实际都在这里面 bindServiceLocked -> bringUpServiceLocked -> bringUpServiceInnerLocked()
首先判断Service是否已经被创建,service已经被创建直接执行sendServiceArgsLocked方法。否则如下流程
判断service进程是否存在,如果不存在会去创建新的进程,存在且service已经准备就绪执行realStartServiceLocked。注如果service进程存在但没有准备就绪在attachApplication的时候还会调到realStartServiceLocked
bringUpServiceInnerLocked() -> realStartServiceLocked(启动实例) -> thread.scheduleCreateService
-> sendServiceArgsLocked() -> thread.scheduleServiceArgs -> onStartCommend //bindeService的时候sendServiceArgsLocked第一个判断就退出了 所以并不会执行onStartCommend
-> requestServiceBindingsLocked() -> requestServiceBindingLocked() -> thread.scheduleBindService() -> Service.onBind()
onBinder之后的回调publishService() -> c.conn.connected(clientSideComponentName, b.intent.binder, false);