Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 4.4 組件分析:bindService 源碼全流程追蹤

編輯:關於 Android 程式設計

由於前面已經詳細分析過 startService 的實作過程,bindService 這邊就不必再逐行細究,重點放在流程串接與幾個容易忽略的細節上。

一、應用層:從 ContextWrapper 到 bindServiceCommon

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());
}

二、AMS 側:bindServiceLocked

接著跨進 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);
    }
}

三、realStartServiceLocked 的三段式

依先前的分析,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 流程。

四、回到應用進程:handleBindService

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 稍後會被送回去給客戶端使用。

五、publishService 與回調的抵達

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 之間形成循環引用而無法被回收。

六、KV 對的建立:getServiceDispatcher

回到 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。

七、最後一哩:onServiceConnected

於是當 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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved