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

Android Service 源碼剖析(三):綁定機制與跨進程 Binder

編輯:關於 Android 程式設計

接續前一篇,這次要處理的是第三個問題:Service 與客戶端的綁定究竟如何實現,也就是跨進程調用的細節。

(一)Service 的生命週期

(二)Service 的自動重啟問題

(三)Service 與客戶端的綁定如何實現,即跨進程調用問題

從 ContextImpl.bindServiceCommon 看起

綁定本質上是透過 Binder 完成的:客戶端呼叫 bind 服務。先看 ContextImpl 的實作:

private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, UserHandle user) {
    IServiceConnection sd;
    if (mPackageInfo != null) {
        sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), mMainThread.getHandler(), flags);
    }
    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();
        int res = ActivityManagerNative.getDefault().bindService(
                mMainThread.getApplicationThread(),
                getActivityToken(), service,
                service.resolveTypeIfNeeded(getContentResolver()),
                sd, flags, user.getIdentifier());
        if (res < 0) {
            throw new SecurityException("Not allowed to bind to service " + service);
        }
        return res != 0;
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
}

LoadedApk 建立跨進程 Binder

接著 LoadedApk 會建立一個用於跨進程連線的 Binder 物件,也就是 ServiceDispatcher 內部的 InnerConnection:

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);
        } else {
            sd.validate(context, handler);
        }
        return sd.getIServiceConnection();
    }
}

ServiceDispatcher 與 InnerConnection

static final class ServiceDispatcher {
    private final ServiceDispatcher.InnerConnection mIServiceConnection;
    private final ServiceConnection mConnection;

    private static class ConnectionInfo {
        IBinder binder;
        IBinder.DeathRecipient deathMonitor;
    }

    private static class InnerConnection extends IServiceConnection.Stub {
        final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;

        InnerConnection(LoadedApk.ServiceDispatcher sd) {
            mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);
        }

        // 這個方法由 ActivityManagerService 在綁定完成後回呼
        // service 就是遠程物件 onBind 所回傳的那個 Binder
        // 這裡才是服務端與客戶端傳遞 Binder 物件的通道
        public void connected(ComponentName name, IBinder service) throws RemoteException {
            LoadedApk.ServiceDispatcher sd = mDispatcher.get();
            if (sd != null) {
                sd.connected(name, service);
            }
        }
    }

    public void connected(ComponentName name, IBinder service) {
        if (mActivityThread != null) {
            mActivityThread.post(new RunConnection(name, service, 0));
        } else {
            doConnected(name, service);
        }
    }

    public void doConnected(ComponentName name, IBinder service) {
        ServiceDispatcher.ConnectionInfo old;
        ServiceDispatcher.ConnectionInfo info;
        synchronized (this) {
            if (mForgotten) {
                // 在回調到達前就已 unbind,直接忽略
                return;
            }
            old = mActiveConnections.get(name);
            if (old != null && old.binder == service) {
                return;
            }
            if (service != null) {
                mDied = false;
                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);
        }
    }

    public void doDeath(ComponentName name, IBinder service) {
        mConnection.onServiceDisconnected(name);
    }
}

bindServiceLocked:真正的綁定流程

int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
        String resolvedType, IServiceConnection connection, int flags, int userId) {

    ServiceLookupResult res = retrieveServiceLocked(service, resolvedType,
            Binder.getCallingPid(), Binder.getCallingUid(), userId, true, callerFg);

    // bindings 中記錄綁定請求,後續 requestServiceBindingsLocked() 處理
    AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);

    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) {
        // 服務已啟動且綁定過,直接發布連線
        try {
            c.conn.connected(s.name, b.intent.binder);
        } catch (Exception e) {
            Slog.w(TAG, "Failure sending service " + s.shortName + " to connection "
                    + c.conn.asBinder(), e);
        }
        // 一般情況下 onBind 只會執行一次,除非請求 doRebind
        if (b.intent.apps.size() == 1 && b.intent.doRebind) {
            requestServiceBindingLocked(s, b.intent, callerFg, true);
        }
    } else if (!b.intent.requested) {
        // 服務尚未綁定過,走後續流程,最終會呼叫 onBind
        requestServiceBindingLocked(s, b.intent, callerFg, false);
    }
    return 1;
}

那 onServiceDisconnected 是誰觸發的

仔細看會發現一個有意思的細節:InnerConnection 裡並沒有 unConnected 方法,unBind 流程中也找不到任何地方呼叫它,那條路徑上只有服務端的 unBind 以及可能的 onDestroy。

答案在 Binder 的死亡通知機制。ServiceDispatcher 在 doConnected 中為遠端 Binder 註冊了一個 IBinder.DeathRecipient(也就是 DeathMonitor)。只有當服務端那個 Binder 真正死亡時,binderDied() 才會被觸發,進而呼叫 doDeath() 並最終回到 ServiceConnection.onServiceDisconnected()。

換句話說,onServiceDisconnected 不是「客戶端解綁」的回調,而是「服務進程掛了」的通知。這兩個語意在實務上常被混淆,理解清楚之後,處理服務異常重連的邏輯就會順很多。

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