編輯:關於 Android 程式設計
在我們日常的 Android 開發中,只要涉及 Service 的雙向通信,就離不開「綁定」這個動作。唯有當 Service 處於已綁定狀態時,客戶端才能拿到一個 Binder 物件,進而與服務端展開交流。這個過程看似水到渠成,背後卻藏著一套精巧的機制。
但你是否真正搞清楚了 Service 綁定的來龍去脈?又為什麼偏偏是 Binder 承擔了與 Service 通信的重任?在深入源碼之前,不妨先看一張流程圖建立整體印象,灰底框內標示的是同一個類的方法:

我們知道,只要呼叫 Context 的 bindService 方法就能完成綁定,而 ContextImpl 正是 Context 的實現類。接下來,就讓我們沿著源碼的脈絡,一步步拆解這個過程。
一切的起點自然是 ContextImpl 的 bindService 方法:
@Override
public boolean bindService(Intent service, ServiceConnection conn, int flags) {
warnIfCallingFromSystemProcess();
return bindServiceCommon(service, conn, flags, mMainThread.getHandler(), Process.myUserHandle());
}
可以看到,它把 Intent 與 ServiceConnection 打包,轉交给了 bindServiceCommon 方法去處理真正的細節。
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, Handler handler, UserHandle user) {
IServiceConnection sd;
if (conn == null) {
throw new IllegalArgumentException("connection is null");
}
if (mPackageInfo != null) {
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);
int res = ActivityManagerNative.getDefault().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();
}
}
關鍵的一行,是呼叫 mPackageInfo(也就是 LoadedApk 物件)的 getServiceDispatcher 方法。顧名思義,這是在取得一個「服務分發者」,而我們真正想要的 Binder,正是透過它換來的。
public final IServiceConnection getServiceDispatcher(ServiceConnection c, Context context, Handler handler, int flags) {
synchronized (mServices) {
LoadedApk.ServiceDispatcher sd = null;
ArrayMap map = mServices.get(context);
if (map != null) {
sd = map.get(c);
}
if (sd == null) {
sd = new ServiceDispatcher(c, context, handler, flags);
if (map == null) {
map = new ArrayMap();
mServices.put(context, map);
}
map.put(c, sd);
} else {
sd.validate(context, handler);
}
return sd.getIServiceConnection();
}
}
從實現不難看出,ServiceConnection 與 ServiceDispatcher 之間構成了一組映射關係。當集合不為空時,系統會以傳入的 ServiceConnection 為 key,取出對應的 ServiceDispatcher;最後一行 return sd.getIServiceConnection() 才是畫龍點睛之筆。
IServiceConnection getIServiceConnection() {
return mIServiceConnection;
}
那麼 mIServiceConnection 究竟是什麼?要回答這個問題,得把目光轉向 ServiceDispatcher 這個內部類。它同時封裝了 InnerConnection 與 ServiceConnection:
static final class ServiceDispatcher {
private final ServiceDispatcher.InnerConnection mIServiceConnection;
private final ServiceConnection mConnection;
private final Context mContext;
private final Handler mActivityThread;
private final ServiceConnectionLeaked mLocation;
private final int mFlags;
private RuntimeException mUnbindLocation;
private boolean mForgotten;
private static class ConnectionInfo {
IBinder binder;
IBinder.DeathRecipient deathMonitor;
}
private static class InnerConnection extends IServiceConnection.Stub {
final WeakReference mDispatcher;
InnerConnection(LoadedApk.ServiceDispatcher sd) {
mDispatcher = new WeakReference(sd);
}
public void connected(ComponentName name, IBinder service) throws RemoteException {
LoadedApk.ServiceDispatcher sd = mDispatcher.get();
if (sd != null) {
sd.connected(name, service);
}
}
}
private final ArrayMap mActiveConnections =
new ArrayMap();
ServiceDispatcher(ServiceConnection conn, Context context, Handler activityThread, int flags) {
mIServiceConnection = new InnerConnection(this);
mConnection = conn;
mContext = context;
mActivityThread = activityThread;
mLocation = new ServiceConnectionLeaked(null);
mLocation.fillInStackTrace();
mFlags = flags;
}
// 其餘程式碼省略
}
看 ServiceDispatcher 的建構子,每個實例都會關聯一個 InnerConnection 物件;而 InnerConnection 本質上就是一個 Binder,並有一個舉足輕重的 connected 方法。之所以非得用 Binder,原因很簡單——與 Service 的通信往往是跨進程的。
把前面的脈絡梳理一遍:呼叫 bindService 綁定服務後,流程轉入 bindServiceCommon;其中呼叫 LoadedApk 的 getServiceDispatcher,把 ServiceConnection 傳入,取出與之映射的 ServiceDispatcher,最後再透過 getIServiceConnection 拿到關聯的 InnerConnection 並返回。一句話概括:用 ServiceConnection 換來了一個 InnerConnection。
回到 bindServiceCommon,可以看到真正的綁定動作最終落在 ActivityManagerNative.getDefault().bindService 上。從它拋出的 RemoteException 也能推斷,這一步必然涉及跨進程通信。而 ActivityManagerNative.getDefault() 返回的,正是 ActivityManagerService。於是我們順藤摸瓜,進入 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");
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);
}
}
真正的邏輯交到了 ActiveServices 的 bindServiceLocked:
int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service, String resolvedType,
final IServiceConnection connection, int flags, String callingPackage, final int userId)
throws TransactionTooLargeException {
// 程式碼省略
ConnectionRecord c = new ConnectionRecord(b, activity, connection, flags, clientLabel, clientIntent);
IBinder binder = connection.asBinder();
ArrayList clist = s.connections.get(binder);
if (clist == null) {
clist = new ArrayList();
s.connections.put(binder, clist);
}
clist.add(c);
// 程式碼省略
if ((flags & Context.BIND_AUTO_CREATE) != 0) {
s.lastActivity = SystemClock.uptimeMillis();
if (bringUpServiceLocked(s, service.getFlags(), callerFg, false, permissionsReviewRequired) != null) {
return 0;
}
}
// 程式碼省略
return 1;
}
這裡有一步至關重要:把 connection(也就是前面提到的 InnerConnection)封裝進 ConnectionRecord。接著流程轉入 bringUpServiceLocked:
private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
boolean whileRestarting, boolean permissionsReviewRequired) throws TransactionTooLargeException {
// 程式碼省略
if (app != null && app.thread != null) {
try {
app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
realStartServiceLocked(r, app, execInFg);
return null;
} catch (TransactionTooLargeException e) {
throw e;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting service " + r.shortName, e);
}
}
// 程式碼省略
return null;
}
此處呼叫了 realStartServiceLocked,終於要正式啟動 Service 了:
private final void realStartServiceLocked(ServiceRecord r, ProcessRecord app, boolean execInFg)
throws RemoteException {
// 程式碼省略
app.thread.scheduleCreateService(r, r.serviceInfo,
mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo), app.repProcState);
r.postNotification();
created = true;
// 程式碼省略
requestServiceBindingsLocked(r, execInFg);
updateServiceClientActivitiesLocked(app, null, true);
if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(), null, null));
}
sendServiceArgsLocked(r, execInFg, true);
// 程式碼省略
}
app.thread.scheduleCreateService 會創建 Service 並回呼其生命週期,那綁定呢?別急,仔細看還有一個 requestServiceBindingsLocked——顧名思義就是「請求綁定服務」,答案就在這裡。
private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
throws TransactionTooLargeException {
for (int i = r.bindings.size() - 1; i >= 0; i--) {
IntentBindRecord ibr = r.bindings.valueAt(i);
if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
break;
}
}
}
private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
boolean execInFg, boolean rebind) throws TransactionTooLargeException {
if (r.app == null || r.app.thread == null) {
return false;
}
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;
}
// 程式碼省略
return true;
}
}
於是 r.app.thread 呼叫 scheduleBindService 來綁定服務。r.app.thread 是 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;
sendMessage(H.BIND_SERVICE, s);
}
它封裝好待綁定的 Service 資訊,向主線程投遞了一則訊息。主線程的 Handler 收到後分派處理:
case BIND_SERVICE:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
handleBindService((BindServiceData) msg.obj);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
handleBindService 一出場,綁定就近在咫尺了:
private void handleBindService(BindServiceData data) {
Service s = mServices.get(data.token);
if (s != null) {
try {
data.intent.setExtrasClassLoader(s.getClassLoader());
data.intent.prepareToEnterProcess();
try {
if (!data.rebind) {
IBinder binder = s.onBind(data.intent);
ActivityManagerNative.getDefault().publishService(data.token, data.intent, binder);
} else {
s.onRebind(data.intent);
ActivityManagerNative.getDefault().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);
}
}
}
}
系統依據 token 找到 Service,回呼 onBind。但故事還沒結束——onBind 回傳的那個 Binder 究竟派什麼用場?答案藏在 publishService 裡。
流程再度回到 ActivityManagerService:
public void publishService(IBinder token, Intent intent, IBinder service) {
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);
}
}
轉入 ActiveServices 的 publishServiceLocked:
void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
final long origId = Binder.clearCallingIdentity();
try {
if (r != null) {
Intent.FilterComparison filter = new Intent.FilterComparison(intent);
IntentBindRecord b = r.bindings.get(filter);
if (b != null && !b.received) {
b.binder = service;
b.requested = true;
b.received = true;
for (int conni = r.connections.size() - 1; conni >= 0; conni--) {
ArrayList clist = r.connections.valueAt(conni);
for (int i = 0; i < clist.size(); i++) {
ConnectionRecord c = clist.get(i);
if (!filter.equals(c.binding.intent.intent)) {
continue;
}
c.conn.connected(r.name, service);
}
}
}
}
} finally {
Binder.restoreCallingIdentity(origId);
}
}
這裡的 c.conn 正是那個 InnerConnection——沒錯,就是前面被封裝進 ConnectionRecord 的那個 Binder。如今它被呼叫 connected 方法,一切便顺理成章了。
public void connected(ComponentName name, IBinder service) throws RemoteException {
LoadedApk.ServiceDispatcher sd = mDispatcher.get();
if (sd != null) {
sd.connected(name, service);
}
}
InnerConnection 的 connected 又轉調 ServiceDispatcher 的 connected:
public void connected(ComponentName name, IBinder service) {
if (mActivityThread != null) {
mActivityThread.post(new RunConnection(name, service, 0));
} else {
doConnected(name, service);
}
}
至此,ActivityThread 向主線程投遞了一則訊息,跨進程通信的難題迎刃而解。而 RunConnection 顯然肩負著在主線程回呼 onServiceConnected 的使命:
private final class RunConnection implements Runnable {
RunConnection(ComponentName name, IBinder service, int command) {
mName = name;
mService = service;
mCommand = command;
}
public void run() {
if (mCommand == 0) {
doConnected(mName, mService);
} else if (mCommand == 1) {
doDeath(mName, mService);
}
}
final ComponentName mName;
final IBinder mService;
final int mCommand;
}
再往裡走,doConnected 終於揭開了最後一層面紗:
public void doConnected(ComponentName name, IBinder service) {
ServiceDispatcher.ConnectionInfo old;
ServiceDispatcher.ConnectionInfo info;
synchronized (this) {
if (mForgotten) {
return;
}
old = mActiveConnections.get(name);
if (old != null && old.binder == service) {
return;
}
if (service != null) {
info = new ConnectionInfo();
info.binder = service;
info.deathMonitor = new DeathMonitor(name, service);
try {
service.linkToDeath(info.deathMonitor, 0);
mActiveConnections.put(name, info);
} catch (RemoteException e) {
mActiveConnections.remove(name);
return;
}
} else {
mActiveConnections.remove(name);
}
if (old != null) {
old.binder.unlinkToDeath(old.deathMonitor, 0);
}
}
if (old != null) {
mConnection.onServiceDisconnected(name);
}
if (service != null) {
mConnection.onServiceConnected(name, service);
}
}
在最後那個 if 判斷裡,我們終於等到了 onServiceConnected!
回顧整條線索:Service 回呼 onBind 並非終點,流程會轉入 ActivityManagerService,再由 ActiveServices 的 publishServiceLocked 從 ConnectionRecord 中取出 InnerConnection,接著回呼它的 connected;connected 又轉調 ServiceDispatcher 的 connected,向主線程投遞訊息完成線程切換,最終在主線程回呼客戶端傳入的 ServiceConnection 的 onServiceConnected。
至此,Service 的綁定過程便徹底清晰了。理解了 Binder 如何在進程之間架起橋樑,也就理解了 Android 系統服務通信的精髓所在。
Android 筆記:Activity 的狀態保存與恢復(含橫竖屏切換)
按 Home 鍵離開時 Activity 不會被銷毀,但如果旋轉螢幕,情況就完全不同了——系統會為了套用新的版面配置而重建整個 Activity,那些只存在記憶體裡的變數
Android 入門:ListView 與 SimpleAdapter 的基本用法(上)
ListView 是 Android 裡最常被用到的控件之一,而它裡面的每一個子項(Item)既可以只是一串文字,也可以是一個由多個控件組成的複合版面。本文先從最基礎的
Android 手寫塗鴉功能實作:自定義 View 保留手寫軌跡
想在一張圖片上自由塗寫,其實並不需要什麼高深技巧。核心概念只有一句話:把使用者手指走過的每一段線,持續畫在同一張 Bitmap 上,然後整張重繪。下面是一個可直接運行的完
Android 屏幕適配實戰:多分辨率下的布局與圖片方案
對剛接觸 Android 的開發者來說,功能做完之後最大的挑戰往往不是邏輯,而是適配——同一份布局,在不同分辨率的機型上顯示效果千差萬別。 先學會查官方文檔 其實 An