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

Service 的工作過程:啟動與綁定的源碼全流程剖析

編輯:關於 Android 程式設計

Service 有兩種工作狀態:一種是啟動狀態,主要用於後台計算;另一種是綁定狀態,主要用於與其他組件交互。兩者並不互斥,一個 Service 完全可以同時處於啟動與綁定狀態。

本文沿著源碼,把這兩條路徑完整走一遍。

一、Service 的啟動過程

第一站:ContextWrapper

@Override
public ComponentName startService(Intent service) {
    return mBase.startService(service);
}

mBase 的實際類型是 ContextImpl。

第二站:ContextImpl

@Override
public ComponentName startService(Intent service) {
    warnIfCallingFromSystemProcess();
    return startServiceCommon(service, mUser);
}

private ComponentName startServiceCommon(Intent service, UserHandle user) {
    try {
        validateServiceIntent(service);
        service.prepareToLeaveProcess();
        ComponentName cn = ActivityManagerNative.getDefault().startService(
                mMainThread.getApplicationThread(),
                service,
                service.resolveTypeIfNeeded(getContentResolver()),
                getOpPackageName(),
                user.getIdentifier());
        // 校驗返回值的省略
        return cn;
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
}

關鍵是 ActivityManagerNative.getDefault(),拿到的就是 AMS。通過 AMS 啟動服務是一次跨進程調用,應用只能把請求交上去,真正的調度在系統進程裡完成。

第三站:AMS#startService

@Override
public ComponentName startService(IApplicationThread caller, Intent service,
        String resolvedType, String callingPackage, int userId)
        throws TransactionTooLargeException {
    enforceNotIsolatedCaller("startService");
    synchronized (this) {
        final int callingPid = Binder.getCallingPid();
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        ComponentName res = mServices.startServiceLocked(caller, service, resolvedType,
                callingPid, callingUid, callingPackage, userId);
        Binder.restoreCallingIdentity(origId);
        return res;
    }
}

AMS 把後續工作交給 mServices,其類型是 ActivityServices——一個輔助 AMS 管理 Service 的類,負責啟動、綁定、停止等各項事宜。

調用鏈是這樣一層層遞進的:startServiceLocked → startServiceInnerLocked → bringUpServiceLocked → realStartServiceLocked。

第四站:ActivityServices#realStartServiceLocked

private final void realStartServiceLocked(ServiceRecord r, ProcessRecord app, boolean execInFg)
        throws RemoteException {
    r.app = app;
    r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
    bumpServiceExecutingLocked(r, execInFg, "create");
    mAm.updateLruProcessLocked(app, false, null);
    mAm.updateOomAdjLocked();

    boolean created = false;
    try {
        mAm.ensurePackageDexOpt(r.serviceInfo.packageName);
        app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
        app.thread.scheduleCreateService(r, r.serviceInfo,
                mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
                app.repProcState);
        r.postNotification();
        created = true;
    } finally {
        if (!created) {
            // 創建失敗時的回滾與重試,代碼省略
        }
    }

    requestServiceBindingsLocked(r, execInFg);
    updateServiceClientActivitiesLocked(app, null, true);

    // 若已處於 started 狀態且無待處理參數,偽造一條以便回調 onStartCommand
    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 負責創建實例並回調 onCreate,sendServiceArgsLocked 負責回調 onStartCommand 等其餘方法。二者最終都落到應用進程的 ApplicationThread 上。

第五站:ApplicationThread#scheduleCreateService

public final void scheduleCreateService(IBinder token, ServiceInfo info,
        CompatibilityInfo compatInfo, int processState) {
    updateProcessState(processState, false);
    CreateServiceData s = new CreateServiceData();
    s.token = token;
    s.info = info;
    s.compatInfo = compatInfo;
    sendMessage(H.CREATE_SERVICE, s);
}

套路與 Activity 啟動如出一轍:把參數包成 Data 對象,丟給 Handler H。

第六站:ActivityThread#handleCreateService

private void handleCreateService(CreateServiceData data) {
    unscheduleGcIdler();
    LoadedApk packageInfo = getPackageInfoNoCheck(data.info.applicationInfo, data.compatInfo);
    Service service = null;
    try {
        ClassLoader cl = packageInfo.getClassLoader();
        service = (Service) cl.loadClass(data.info.name).newInstance();
    } catch (Exception e) {
        throw new RuntimeException("Unable to instantiate service " + data.info.name, e);
    }
    try {
        ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
        context.setOuterContext(service);
        Application app = packageInfo.makeApplication(false, mInstrumentation);
        service.attach(context, this, data.info.name, data.token, app,
                ActivityManagerNative.getDefault());
        service.onCreate();
        mServices.put(data.token, service);
        ActivityManagerNative.getDefault().serviceDoneExecuting(
                data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
    } catch (Exception e) {
        throw new RuntimeException("Unable to create service " + data.info.name, e);
    }
}

這一段做了四件事:

  1. 通過類加載器反射創建 Service 實例;
  2. 創建(或復用)Application 對象並確保其 onCreate 已執行;
  3. 構建 ContextImpl 並通過 service.attach() 把二者關聯起來,與 Activity 的處理思路一致;
  4. 調用 Service 的 onCreate,再把 Service 存入 ActivityThread 的 mServices 列表,最後通知 AMS「我執行完了」。

onCreate 執行完畢,Service 也就啟動了。隨後 ActivityThread 還會通過 handleServiceArgs 回調 onStartCommand:

private void handleServiceArgs(ServiceArgsData data) {
    Service s = mServices.get(data.token);
    if (s != null) {
        int res;
        if (!data.taskRemoved) {
            res = s.onStartCommand(data.args, data.flags, data.startId);
        } else {
            s.onTaskRemoved(data.args);
            res = Service.START_TASK_REMOVED_COMPLETE;
        }
        QueuedWork.waitToFinish();
        ActivityManagerNative.getDefault().serviceDoneExecuting(
                data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
    }
}

二、Service 的綁定過程

第一站:ContextWrapper → ContextImpl

private boolean bindServiceCommon(Intent service, ServiceConnection conn, int flags, UserHandle user) {
    IServiceConnection sd;
    if (conn == null) throw new IllegalArgumentException("connection is null");
    sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(),
            mMainThread.getHandler(), flags);
    validateServiceIntent(service);
    try {
        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 new RuntimeException("Failure from system", e);
    }
}

注意這裡做了一次關鍵的對象轉換:把客戶端的 ServiceConnection 包裝成 ServiceDispatcher.InnerConnection。因為綁定往往是跨進程的,ServiceConnection 必須借助 Binder 才能讓遠端服務回調自己的方法,而 InnerConnection 正好扮演了這個 Binder 的角色;ServiceDispatcher 則負責連接 ServiceConnection 與 InnerConnection。

插曲:LoadedApk#getServiceDispatcher

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

mServices 用 ArrayMap 保存了「Context → (ServiceConnection → ServiceDispatcher)」的映射。若查到相同 ServiceConnection 就復用並校驗,否則新建一個 ServiceDispatcher 存起來。ServiceDispatcher 內部同時持有 ServiceConnection 與 InnerConnection,等連接建立後,系統正是通過 InnerConnection 去調用客戶端的 onServiceConnected。

AMS#bindService 之後的調用鏈與啟動過程高度重合:AMS → ActivityServices#bindServiceLocked → startServiceInnerLocked → bringUpServiceLocked → realStartServiceLocked,最終仍由 ApplicationThread 完成 Service 實例的創建與 onCreate 回調。差別在於綁定流程會額外調用 app.thread.scheduleBindService:

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

ActivityThread#handleBindService

private void handleBindService(BindServiceData data) {
    Service s = mServices.get(data.token);
    if (s != null) {
        try {
            data.intent.prepareToEnterProcess();
            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);
            }
        } catch (Exception e) {
            throw new RuntimeException("Unable to bind to service " + s, e);
        }
    }
}

先按 token 取出 Service,再調 onBind 拿到要交給客戶端的 Binder。原則上 onBind 返回後 Service 就算綁定成功,但客戶端此時還不知道,所以還得走一趟 publishService 去回調客戶端的 onServiceConnected。

順帶記住一個特性:多次綁定同一個 Service 時,onBind 只會執行一次(除非 Service 被銷毀),後續綁定走的是 onRebind 分支。

AMS#publishService → ActivityServices#publishServiceLocked

核心只有一行:

c.conn.connected(r.name, service);

其中 c 是 ConnectionRecord,c.conn 就是 ServiceDispatcher.InnerConnection,service 則是 onBind 返回的 Binder。

InnerConnection#connected

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

    public void connected(ComponentName name, IBinder service) throws RemoteException {
        LoadedApk.ServiceDispatcher sd = mDispatcher.get();
        if (sd != null) sd.connected(name, service);
    }
}

ServiceDispatcher#connected

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

mActivityThread 就是 ActivityThread 的 Handler H。通過 post 拋給 H,客戶端 ServiceConnection 的回調因此運行在主線程——這一點在寫 onServiceConnected 裡的邏輯時必須牢記,不能在裡面做耗時操作。

ServiceDispatcher#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) {
            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);
}

這裡順帶處理了服務進程死亡的情形:通過 linkToDeath 掛上死亡監聽,一旦對端進程掛掉,客戶端會收到 onServiceDisconnected。而 mForgotten 的判斷則保證了「已解綁之後才姗姗來遲的連接回調」不會誤觸業務。

客戶端的 onServiceConnected 執行完畢,整個綁定過程也就收尾了。

三、總結

把兩條鏈路並排看,規律其實很清楚:

  • 應用側的入口都在 ContextWrapper,真正邏輯在 ContextImpl;
  • 凡是跨進程的請求一律交給 AMS,由 ActivityServices 承擔具體調度;
  • AMS 從不直接操作 Service 對象,而是通過 ApplicationThread 發消息,回到應用進程的 Handler H,最終由 ActivityThread 完成實例化與生命周期回調;
  • 綁定比啟動多出的那一環,是 InnerConnection 與 publishService——前者解決跨進程 Binder 問題,後者負責把 onBind 的結果送達客戶端,並保證回調在主線程執行。

理解了這套「AMS 中轉 + Handler 消息 + Binder 回調」的三段式結構,再去看 Service 的銷毀、重啟、以及與 Activity 的交互,都會順暢很多。

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