編輯:關於 Android 程式設計
由於前面已經詳細分析過 startService 的實作過程,bindService 這邊就不必再逐行細究,重點放在流程串接與幾個容易忽略的細節上。
bindService 的起點同樣是 ContextWrapper.bindService,接著進入 ContextImpl 的 bindService,最後抵達 bindServiceCommon。這裡第一個關鍵細節是:傳入的 ServiceConnection 會被轉換成 IServiceConnection 類型。
private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags,
UserHandle user) {
IServiceConnection sd;
...
sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
mMainThread.getHandler(), flags);
...
int res = ActivityManagerNative.getDefault().bindService(
mMainThread.getApplicationThread(), getActivityToken(),
service, service.resolveTypeIfNeeded(getContentResolver()),
sd, flags, user.getIdentifier());
}
接著跨進 System 進程的 AMS,再由它調用 ActiveServices.java 的 bindServiceLocked。這裡會把 IServiceConnection 實例包進 ConnectionRecord,並視情況執行 bringUpServiceLocked。
int bindServiceLocked(IApplicationThread caller, IBinder token,
Intent service, String resolvedType,
IServiceConnection connection, int flags, int userId) {
...
ConnectionRecord c = new ConnectionRecord(b, activity,
connection, flags, clientLabel, clientIntent);
IBinder binder = connection.asBinder();
if ((flags & Context.BIND_AUTO_CREATE) != 0) {
s.lastActivity = SystemClock.uptimeMillis();
if (bringUpServiceLocked(s, service.getFlags(), callerFg, false) != null) {
return 0;
}
}
...
if (s.app != null && b.intent.received) {
// Service 已在運行,可以直接發布連接
try {
c.conn.connected(s.name, b.intent.binder);
} catch (Exception e) { ... }
// 若是第一個 App 連回這個 binding,且服務先前要求過
// 被重新綁定時要通知它,這裡就處理這件事
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);
}
}
依先前的分析,bindServiceLocked 會走到 realStartServiceLocked。這個方法裡其實一次做了三件事,順序非常關鍵:
private final void realStartServiceLocked(ServiceRecord r,
ProcessRecord app, boolean execInFg) throws RemoteException {
...
// 1. 建立服務並回調 onCreate()
app.thread.scheduleCreateService(r, r.serviceInfo,
mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
app.repProcState);
...
// 2. bind 相關的處理
requestServiceBindingsLocked(r, execInFg);
// 3. start 相關的處理
sendServiceArgsLocked(r, execInFg, true);
...
}
也就是說,無論你是用 startService 還是 bindService,服務的 onCreate() 都會先被執行;差別只在後續是走 binding 流程還是 onStartCommand 流程。
requestServiceBindingsLocked 再往下調用 ActivityThread 的 scheduleBindService,在 ActivityThread.java 中它會發出一個 BIND_SERVICE 事件,最終由 handleBindService 處理:
private void handleBindService(BindServiceData data) {
...
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, 0, 0, 0);
}
...
}
這裡先調用服務的 onBind()。由於具體服務類別覆寫了這個方法,因此會執行我們自己寫的邏輯,並回傳服務內部的 Binder 實例;這個 Binder 稍後會被送回去給客戶端使用。
AMS 的 publishService 又會調用 ActiveServices.java 的 publishServiceLocked:
void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
...
for (int conni = r.connections.size() - 1; conni >= 0; conni--) {
ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
for (int i = 0; i < clist.size(); i++) {
ConnectionRecord c = clist.get(i);
...
try {
c.conn.connected(r.name, service);
} ...
}
}
serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
}
這裡的核心就是 c.conn.connected。c 是 ConnectionRecord,其成員 conn 是一個 IServiceConnection 類型的實例。
IServiceConnection 是一個 AIDL 接口,位於 frameworks/base 下的 core/java/android/app/IServiceConnection.aidl,定義極為簡潔,只有一個方法:
oneway interface IServiceConnection {
void connected(in ComponentName name, IBinder service);
}
它的服務端實作在 LoadedApk.java 中。InnerConnection 是 ServiceDispatcher 的內部類,在 ServiceDispatcher 的建構子裡被實例化,而它的 connected 方法只是轉手呼叫 ServiceDispatcher 自己的 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)
throws RemoteException {
LoadedApk.ServiceDispatcher sd = mDispatcher.get();
if (sd != null) {
sd.connected(name, service);
}
}
}
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;
}
注意這裡用的是 WeakReference 而非強引用,避免 ServiceDispatcher 與 InnerConnection 之間形成循環引用而無法被回收。
回到 ContextImpl 的 bindServiceCommon,做 ServiceConnection 到 IServiceConnection 轉換時呼叫的 mPackageInfo.getServiceDispatcher,其中 mPackageInfo 就是一個 LoadedApk 實例。這個方法會建立 ServiceDispatcher 實例,並把「ServiceConnection → ServiceDispatcher」形成一組 KV 對存起來:
public final IServiceConnection getServiceDispatcher(ServiceConnection c,
Context context, Handler handler, int flags) {
synchronized (mServices) {
LoadedApk.ServiceDispatcher sd = null;
ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> 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<ServiceConnection, LoadedApk.ServiceDispatcher>();
mServices.put(context, map);
}
map.put(c, sd);
}
...
}
}
而在 ServiceDispatcher 的建構子中,傳入的 ServiceConnection 被賦值給成員變數 mConnection。
於是當 ServiceDispatcher 的 connected 方法被執行時,就會回頭調用 mConnection 上的:
public void doConnected(ComponentName name, IBinder service) {
...
if (old != null) {
mConnection.onServiceDisconnected(name);
}
// 若有新的服務,代表現在已連上
if (service != null) {
mConnection.onServiceConnected(name, service);
}
}
至此,我們在 App 中覆寫的 onServiceConnected 終於被觸發,整個 bindService 的流程也就走完了。
把上面這一整條鏈路濃縮起來看:
ContextWrapper.bindService → ContextImpl.bindServiceCommon(ServiceConnection 被包成 ServiceDispatcher/InnerConnection)→ AMS.bindService → ActiveServices.bindServiceLocked → realStartServiceLocked(scheduleCreateService 走 onCreate → requestServiceBindingsLocked)→ ActivityThread.handleBindService(呼叫 onBind,取得 Binder)→ AMS.publishService → publishServiceLocked → IServiceConnection.connected → ServiceDispatcher.doConnected → ServiceConnection.onServiceConnected。
從這條鏈路可以讀出幾個實務上的結論:onCreate 必定早於 onBind;onBind 的回傳值會經過一次跨進程往返才回到客戶端,因此 onServiceConnected 一定是非同步抵達的,呼叫 bindService 之後立刻假設服務已連上是不安全的寫法;而 ServiceDispatcher 的 KV 對快取機制,保證了同一個 ServiceConnection 在同一個 Context 下重複 bindService 時,不會產生多個 dispatcher。
從零開始:Eclipse 搭建 Android 開發環境(ADT + Android 4.4.2)
用 Eclipse 做 Android 開發,第一步是把 ADT(Android Development Tools)插件裝上去。整個流程可以拆成 JDK、Eclipse
用 HttpClient 實作手機號碼歸屬地查詢:Android 網路請求完整範例
資料來源 https://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx 該服務除了 HTTP GET/PO
Android 主題切換實戰:白天與夜間模式怎麼做
智慧型手機迅速普及,也大幅改變了我們的生活習慣。很多人習慣睡前滑一會兒手機,但一般應用的日間模式亮度偏高,對眼睛其實是種負擔。因此現在的應用多半會提供「日間/夜間」兩套模
自定義 View 實現彈幕:垂直固定與隨機兩種模式
這次要實現兩種彈幕效果:一種是彈幕在垂直方向位置固定,另一種是垂直方向隨機分佈。 效果一:垂直方向固定 效果二:垂直方向隨機 效果圖中的白色背景就是彈幕容器本身。這