一.前言
通過(guò)上篇IPC之Binder連接池機(jī)制Binder連接池機(jī)制
,我們知道通過(guò)bindService方法能完成整個(gè)服務(wù)的綁定操作,并且通過(guò)onBind回調(diào)方法返回IBinder實(shí)例,在客戶端通過(guò)ServiceConnection#onServiceConnected方法得到IBinder這個(gè)實(shí)例。接下來(lái)我們從源碼的角度來(lái)分析下綁定服務(wù)的工作過(guò)程。
二.工作過(guò)程
大致流程:首先調(diào)用Context#bindService抽象方法,然后我們看Context類的實(shí)現(xiàn)類ContextImpl#bindService,然后跨進(jìn)程調(diào)用到ActivityManagerService中,然后通過(guò)IApplicationThread回調(diào)到ActivityThread.ApplicationThread#scheduleBindService方法中通過(guò)mH(Hander)切換到主線程中ActivityThread#handleBindService處理。下面詳細(xì)的分析工作過(guò)程。
Intent intent = new Intent(context, BinderPoolService.class);
context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
以上調(diào)用流程如下:

1.實(shí)現(xiàn)Context的ContextImpl
public boolean bindService(Intent service, ServiceConnection conn,
int flags) {
warnIfCallingFromSystemProcess();
return bindServiceCommon(service, conn, flags, mMainThread.getHandler(), getUser());
}
然后直接調(diào)用bindServiceCommon方法:
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, Handler
handler, UserHandle user) {
//省略。。。
if (mPackageInfo != null) {
sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), handler, flags);
} else {
throw new RuntimeException("Not supported in system context");
}
//省略。。。
int res = ActivityManager.getService().bindService(
mMainThread.getApplicationThread(), getActivityToken(), service,
service.resolveTypeIfNeeded(getContentResolver()),
sd, flags, 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();
}
}
bindServiceCommon方法主要工作是對(duì)ServiceConnection實(shí)例做一些封裝成可跨進(jìn)程的實(shí)例為后面回調(diào)做鋪墊,相應(yīng)校驗(yàn)以及通過(guò)IActivityManager接口跨進(jìn)程調(diào)用到ActivityManagerService(AMS)中。
2.AMS#bindService
public int bindService(IApplicationThread caller, IBinder token, Intent service,
String resolvedType, IServiceConnection connection, int flags, String callingPackage,
int userId) throws TransactionTooLargeException {
enforceNotIsolatedCaller("bindService");
// Refuse possible leaked file descriptors
if (service != null && service.hasFileDescriptors() == true) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}
if (callingPackage == null) {
throw new IllegalArgumentException("callingPackage cannot be null");
}
synchronized(this) {
return mServices.bindServiceLocked(caller, token, service,
resolvedType, connection, flags, callingPackage, userId);
}
}
3.ActiveServices#bindServiceLocked
通過(guò)上面2可以看到直接調(diào)用ActiveServices#bindServiceLocked方法。
bindServiceLocked方法邏輯比較多,這里重點(diǎn)關(guān)注bind過(guò)程就可以了,所以我們直接看bindServiceLocked方法中調(diào)用requestServiceBindingLocked的邏輯
//省略。。。
if (s.app != null && b.intent.received) {
// Service is already running, so we can immediately
// publish the connection.
try {
c.conn.connected(s.name, b.intent.binder, false);
} catch (Exception e) {
Slog.w(TAG, "Failure sending service " + s.shortName
+ " to connection " + c.conn.asBinder()
+ " (in " + c.binding.client.processName + ")", e);
}
// If this is the first app connected back to this binding,
// and the service had previously asked to be told when
// rebound, then do so.
if (b.intent.apps.size() == 1 && b.intent.doRebind) {
requestServiceBindingLocked(s, b.intent, callerFg, true);
}
} else if (!b.intent.requested) {
requestServiceBindingLocked(s, b.intent, callerFg, false);
}
//省略。。。
接下來(lái)看看requestServiceBindingLocked方法
private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
boolean execInFg, boolean rebind) throws TransactionTooLargeException {
if (r.app == null || r.app.thread == null) {
// If service is not currently running, can't yet bind.
return false;
}
if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
+ " rebind=" + rebind);
if ((!i.requested || rebind) && i.apps.size() > 0) {
try {
bumpServiceExecutingLocked(r, execInFg, "bind");
r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
r.app.repProcState);
if (!rebind) {
i.requested = true;
}
i.hasBound = true;
i.doRebind = false;
} catch (TransactionTooLargeException e) {
// Keep the executeNesting count accurate.
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
final boolean inDestroying = mDestroyingServices.contains(r);
serviceDoneExecutingLocked(r, inDestroying, inDestroying);
throw e;
} catch (RemoteException e) {
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
// Keep the executeNesting count accurate.
final boolean inDestroying = mDestroyingServices.contains(r);
serviceDoneExecutingLocked(r, inDestroying, inDestroying);
return false;
}
}
return true;
}
重點(diǎn)關(guān)注 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
r.app.repProcState);這句邏輯。r.app.thread其實(shí)就是ApplicationThread實(shí)例,在客戶端通過(guò)mMainThread.getApplicationThread()傳給ActivityServices中ServiceRecord記錄的。這里其實(shí)就通過(guò)IApplicationThread跨進(jìn)程回調(diào)到ActivityThread#ApplicationThread#scheduleBindService方法中?;卣{(diào)到4.
4.ActivityThread#ApplicationThread
public final void scheduleBindService(IBinder token, Intent intent,
boolean rebind, int processState) {
updateProcessState(processState, false);
BindServiceData s = new BindServiceData();
s.token = token;
s.intent = intent;
s.rebind = rebind;
if (DEBUG_SERVICE)
Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
+ Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
sendMessage(H.BIND_SERVICE, s);
}
通過(guò)mH切換到主線程處理
private void handleBindService(BindServiceData data) {
Service s = mServices.get(data.token);
if (DEBUG_SERVICE)
Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
if (s != null) {
try {
data.intent.setExtrasClassLoader(s.getClassLoader());
data.intent.prepareToEnterProcess();
try {
if (!data.rebind) {
//1.調(diào)用Service中的onBind方法獲取IBinder接口
IBinder binder = s.onBind(data.intent);
//2.通過(guò)IActivityManager接口跨進(jìn)程調(diào)用到AMS中
ActivityManager.getService().publishService(
data.token, data.intent, binder);
} else {
s.onRebind(data.intent);
ActivityManager.getService().serviceDoneExecuting(
data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
}
ensureJitEnabled();
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
} catch (Exception e) {
if (!mInstrumentation.onException(s, e)) {
throw new RuntimeException(
"Unable to bind to service " + s
+ " with " + data.intent + ": " + e.toString(), e);
}
}
}
}
handleBindService方法中調(diào)用Service中的onBind方法獲取IBinder接口,然后跨進(jìn)程發(fā)布服務(wù)到AMS中。
5.AMS
public void publishService(IBinder token, Intent intent, IBinder service) {
// Refuse possible leaked file descriptors
if (intent != null && intent.hasFileDescriptors() == true) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}
synchronized(this) {
if (!(token instanceof ServiceRecord)) {
throw new IllegalArgumentException("Invalid service token");
}
mServices.publishServiceLocked((ServiceRecord)token, intent, service);
}
}
直接調(diào)用到ActiveServices#publishServiceLocked
6.ActiveServices#publishServiceLocked
void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
//省略。。。
try {
if (b != null && !b.received) {
for (int conni=r.connections.size()-1; conni>=0; conni--) {
try {
c.conn.connected(r.name, service, false);
} catch (Exception e) {
Slog.w(TAG, "Failure sending service " + r.name +
" to connection " + c.conn.asBinder() +
" (in " + c.binding.client.processName + ")", e);
}
}
}
//省略。。。
}
} finally {
Binder.restoreCallingIdentity(origId);
}
}
重點(diǎn)看c.conn.connected(r.name, service, false)方法。調(diào)用到LoadApk#connected方法
7.LoadApk#connected
private static class InnerConnection extends IServiceConnection.Stub {
final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;
InnerConnection(LoadedApk.ServiceDispatcher sd) {
mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);
}
public void connected(ComponentName name, IBinder service, boolean dead)
throws RemoteException {
LoadedApk.ServiceDispatcher sd = mDispatcher.get();
if (sd != null) {
sd.connected(name, service, dead);
}
}
}
通過(guò)doConnected方法最終會(huì)回調(diào)到前面當(dāng)成功綁定一個(gè)服務(wù)的時(shí)候onServiceConnected方法中。這個(gè)時(shí)候整個(gè)綁定服務(wù)過(guò)程就完成了。
public void doConnected(ComponentName name, IBinder service, boolean dead) {
。。。
// If there was an old service, it is now disconnected.
if (old != null) {
mConnection.onServiceDisconnected(name);
}
if (dead) {
mConnection.onBindingDied(name);
}
// If there is a new viable service, it is now connected.
if (service != null) {
mConnection.onServiceConnected(name, service);
} else {
// The binding machinery worked, but the remote returned null from onBind().
mConnection.onNullBinding(name);
}
}
三.總結(jié)
服務(wù)組件的啟動(dòng)分為startService和bindService兩種方式,這里bind啟動(dòng)服務(wù)就上面這幾步過(guò)程。startService過(guò)程差不多,這里就不分析了。