1. 程式人生 > >Android服務之startService原始碼分析

Android服務之startService原始碼分析

先看下繼承關係:

startService是Context的抽象方法,呼叫startService時,會先呼叫到ContextWrapper的startService方法:

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


mBase是ContextImpl的例項,ContextWrapper類的startService方法最終通過ContextImpl類的startService方法來實現:

private ContextImpl(ContextImpl container, ActivityThread mainThread,
        LoadedApk packageInfo, IBinder activityToken, UserHandle user, boolean restricted,
        Display display, Configuration overrideConfiguration, int createDisplayWithId) {
    ...
    // mUser和mMainThread是在構造方法裡面賦的值
    mUser = user;
    mMainThread = mainThread;
    ...
}

@Override
public ComponentName startService(Intent service) {
    warnIfCallingFromSystemProcess();
    // mUser是UserHandle的例項,UserHandle實現了Parcelable介面
    return startServiceCommon(service, mUser);
}

/**
 * Logs a warning if the system process directly called a method such as
 * {@link #startService(Intent)} instead of {@link #startServiceAsUser(Intent, UserHandle)}.
 * The "AsUser" variants allow us to properly enforce the user's restrictions.
 */
private void warnIfCallingFromSystemProcess() {
    // 如果是系統程序呼叫startService方法會列印一個log。
    if (Process.myUid() == Process.SYSTEM_UID) {
        Slog.w(TAG, "Calling a method in the system process without a qualified user: "
                + Debug.getCallers(5));
    }
}

private ComponentName startServiceCommon(Intent service, UserHandle user) {
    try {
        // 驗證intent的有效性
        validateServiceIntent(service);
        // 準備離開應用程式程序,進入ActivityManagerService程序(意味著bundle的資料要在程序間傳遞)
        service.prepareToLeaveProcess();
        // 呼叫ActivityManagerProxy類的startService來實現啟動服務的操作
        // ActivityManagerProxy是一個Binder物件的遠端介面,而這個Binder物件就是ActivityManagerService。
        ComponentName cn = ActivityManagerNative.getDefault().startService(
            mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(
                        getContentResolver()), getOpPackageName(), user.getIdentifier());
        if (cn != null) {
            // 許可權校驗失敗
            if (cn.getPackageName().equals("!")) {
                throw new SecurityException(
                        "Not allowed to start service " + service
                        + " without permission " + cn.getClassName());
            } else if (cn.getPackageName().equals("!!")) {
                throw new SecurityException(
                        "Unable to start service " + service
                        + ": " + cn.getClassName());
            }
        }
        return cn;
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
}


一個程序對應一個ActivityThread例項,這個程序中所有的Activity對應這一個ActivityThread例項。

在ActivityThread類中,有一個成員變數mAppThread,它是一個ApplicationThread例項,它實現了IApplicationThread介面,它的作用是用來輔助ActivityThread執行一些操作。

mMainThread.getApplicationThread()  得到的是當前啟動服務程序(呼叫者)的ApplicationThread物件

service.resolveTypeIfNeeded(getContentResolver())  得到的是intent的MIME資料型別,它是在解析intent時用到的

getOpPackageName()  得到的是呼叫者的包名

private void validateServiceIntent(Intent service) {
    // 隱式啟動判斷,5.1之後不允許隱式啟動服務
    if (service.getComponent() == null && service.getPackage() == null) {
        if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
            IllegalArgumentException ex = new IllegalArgumentException(
                    "Service Intent must be explicit: " + service);
            throw ex;
        } else {
            Log.w(TAG, "Implicit intents with startService are not safe: " + service
                    + " " + Debug.getCallers(2, 3));
        }
    }
}


ActivityManagerNative類中的getDefault方法通過單例模式建立ActivityManagerProxy代理物件。

實現繼承關係:

ActivityManagerNative類:

/**
 * Retrieve the system's default/global activity manager.
 */
static public IActivityManager getDefault() {
    return gDefault.get();
}

private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
    protected IActivityManager create() {
        // 服務查詢,返回BinderProxy物件
        IBinder b = ServiceManager.getService("activity");
        if (false) {
            Log.v("ActivityManager", "default service binder = " + b);
        }
        // 建立與特定業務相關的代理物件
        IActivityManager am = asInterface(b);
        if (false) {
            Log.v("ActivityManager", "default service = " + am);
        }
        return am;
    }
};

/**
 * Cast a Binder object into an activity manager interface, generating
 * a proxy if needed.
 */
static public IActivityManager asInterface(IBinder obj) {
    if (obj == null) {
        return null;
    }
    // 如果之前已經建立過,則直接返回
    IActivityManager in =
        (IActivityManager)obj.queryLocalInterface(descriptor);
    if (in != null) {
        return in;
    }

    // 返回一個ActivityManagerProxy物件
    return new ActivityManagerProxy(obj);
}


Singleton.java抽象類是用懶載入實現的,以後可以參考:

/**
 * Singleton helper class for lazily initialization.
 *
 * @hide
 */
public abstract class Singleton<T> {
    private T mInstance;

    protected abstract T create();

    public final T get() {
        synchronized (this) {
            if (mInstance == null) {
                mInstance = create();
            }
            return mInstance;
        }
    }
}


ActivityManagerProxy類的startService方法把傳遞進來的引數寫入到data本地變數中,接著通過mRemote.transact方法進入到Binder驅動程式,然後Binder驅動程式喚醒正在等待Client請求的ActivityManagerService程序,最後進入到ActivityManagerService的startService方法中,這裡先看一下時序圖:

public ActivityManagerService(Context systemContext) {
    ...
    // mServices在構造方法中賦初值
    mServices = new ActiveServices(this);
    ...
}

@Override
public ComponentName startService(IApplicationThread caller, Intent service,
        String resolvedType, String callingPackage, int userId)
        throws TransactionTooLargeException {
    // 執行呼叫者不能是獨立程序的判斷
    enforceNotIsolatedCaller("startService");
    // Refuse possible leaked file descriptors
    if (service != null && service.hasFileDescriptors() == true) {
        // service中不能攜帶檔案描述符
        throw new IllegalArgumentException("File descriptors passed in Intent");
    }

    if (callingPackage == null) {
        throw new IllegalArgumentException("callingPackage cannot be null");
    }

    if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
            "startService: " + service + " type=" + resolvedType);

    /*可以在這裡準備自啟動的黑白名單初始化操作*/

    synchronized(this) {
        final int callingPid = Binder.getCallingPid();
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        // 呼叫ActiveServices類的startServiceLocked方法
        ComponentName res = mServices.startServiceLocked(caller, service,
                resolvedType, callingPid, callingUid, callingPackage, userId);
        Binder.restoreCallingIdentity(origId);
        return res;
    }
}

void enforceNotIsolatedCaller(String caller) {
    // 根據uid判斷該uid是不是獨立的
    if (UserHandle.isIsolated(Binder.getCallingUid())) {
        throw new SecurityException("Isolated process not allowed to call " + caller);
    }
}


執行到ActiveServices類中的startServiceLocked方法:

public ActiveServices(ActivityManagerService service) {
    // 構造方法中給mAm賦初值
    mAm = service;
    ...
}

ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
        int callingPid, int callingUid, String callingPackage, int userId)
        throws TransactionTooLargeException {
    if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
            + " type=" + resolvedType + " args=" + service.getExtras());

    final boolean callerFg;
    if (caller != null) {
        // 通過ApplicationThread物件從ActivityManagerService的成員變數mLruProcesses
        // 列表中查詢啟動服務的程序(呼叫者)在ActivityManagerService中的ProcessRecord物件,
        // 變數mLruProcesses的說明是:
        /**
         * List of running applications, sorted by recent usage.
         * The first entry in the list is the least recently used.
         */
        final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
        if (callerApp == null) {
            throw new SecurityException(
                    "Unable to find app for caller " + caller
                    + " (pid=" + Binder.getCallingPid()
                    + ") when starting service " + service);
        }
        callerFg = callerApp.setSchedGroup != Process.THREAD_GROUP_BG_NONINTERACTIVE;
    } else {
        callerFg = true;
    }

    // 呼叫retrieveServiceLocked方法解析service這個Intent,然後將解析結果放在res.record中。
    // 呼叫該方法後,為被呼叫者構造了對應的ServiceRecord物件,並儲存到ActivityManagerService的成員變數mServiceMap中。
    ServiceLookupResult res =
        retrieveServiceLocked(service, resolvedType, callingPackage,
                callingPid, callingUid, userId, true, callerFg);
    // 沒有註冊Service
    if (res == null) {
        return null;
    }
    if (res.record == null) {
        return new ComponentName("!", res.permission != null
                ? res.permission : "private to package");
    }

    // caller是呼叫者,r是被呼叫者
    ServiceRecord r = res.record;

    if (!mAm.getUserManagerLocked().exists(r.userId)) {
        Slog.d(TAG, "Trying to start service with non-existent user! " + r.userId);
        return null;
    }

    /*可以新增關聯喚醒的判斷邏輯:如根據被呼叫者包名/類名字首判斷是否屬於第三方push平臺在開啟服務,如果是則直接返回r.name*/

    /*可以新增自啟動的判斷邏輯:如被呼叫者包名在禁止自啟動的列表中,則直接返回r.name*/

    // 許可權檢查
    NeededUriGrants neededGrants = mAm.checkGrantUriPermissionFromIntentLocked(
            callingUid, r.packageName, service, service.getFlags(), null, r.userId);
    if (unscheduleServiceRestartLocked(r, callingUid, false)) {
        if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
    }
    // 初始化服務端的ServiceRecord資訊
    r.lastActivity = SystemClock.uptimeMillis();
    r.startRequested = true;
    r.delayedStop = false;
    r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
            service, neededGrants));

    final ServiceMap smap = getServiceMap(r.userId);
    boolean addToStarting = false;

    // 判斷是否需要延遲啟動,需要則直接返回,不需要則addToStarting設為true
    ...

    return startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
}


ActivityManagerService在請求Zygote程序孵化新的應用程式程序時,在ActivityManagerService服務端為每一個應用程序建立了對應的ProcessRecord物件來描述新的應用程式程序資訊。startServiceLocked方法首先根據應用程式程序中的IApplicationThread物件在最近啟動的應用程式列表mLruProcesses中為服務啟動程序查詢對應的ProcessRecord物件,如果啟動Service的應用程式程序(呼叫者)還未啟動,則拋異常。

然後呼叫retrieveServiceLocked方法為要啟動的Service(被呼叫者)在ActivityManagerService服務端建立一個ServiceRecord物件來描述Service資訊。

ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
        boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
    
    . . .
    String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false);
    if (error != null) {
        return new ComponentName("!!", error);
    }

    . . .

    return r.name;
}

private final String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
        boolean whileRestarting) throws TransactionTooLargeException {

    // 如果該Service已經建立,再次呼叫startService時,只調用該Service的onStartCommand來執行該Service
    if (r.app != null && r.app.thread != null) {
        // 啟動Service
        sendServiceArgsLocked(r, execInFg, false);
        return null;
    }

    if (!whileRestarting && r.restartDelay > 0) {
        // If waiting for a restart, then do nothing.
        return null;
    }

    if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent);

    // We are now bringing the service up, so no longer in the
    // restarting state.
    if (mRestartingServices.remove(r)) {
        r.resetRestartCounter();
        clearRestartingIfNeededLocked(r);
    }

    // Make sure this service is no longer considered delayed, we are starting it now.
    if (r.delayed) {
        if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
        getServiceMap(r.userId).mDelayedStartList.remove(r);
        r.delayed = false;
    }

    // Make sure that the user who owns this service is started.  If not,
    // we don't want to allow it to run.
    if (mAm.mStartedUsers.get(r.userId) == null) {
        String msg = "Unable to launch app "
                + r.appInfo.packageName + "/"
                + r.appInfo.uid + " for service "
                + r.intent.getIntent() + ": user " + r.userId + " is stopped";
        Slog.w(TAG, msg);
        bringDownServiceLocked(r);
        return msg;
    }

    // Service is now being launched, its package can't be stopped.
    try {
        AppGlobals.getPackageManager().setPackageStoppedState(
                r.packageName, false, r.userId);
    } catch (RemoteException e) {
    } catch (IllegalArgumentException e) {
        Slog.w(TAG, "Failed trying to unstop package "
                + r.packageName + ": " + e);
    }

    // 判斷此Service是否在獨立程序中啟動
    final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
    // 得到的是在XML中設定該Service的程序名
    final String procName = r.processName;
    ProcessRecord app;

    if (!isolated) {
        // 根據程序名、uid從ActivityManagerService的成員變數mProcessNames中查詢程序對應的描述符ProcessRecord
        app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
        if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
                    + " app=" + app);
        if (app != null && app.thread != null) {
            try {
                app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
                // 在現有的程序中啟動Service
                realStartServiceLocked(r, app, execInFg);
                return null;
            } catch (TransactionTooLargeException e) {
                throw e;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting service " + r.shortName, e);
            }
        }
    } else {
        // If this service runs in an isolated process, then each time
        // we call startProcessLocked() we will get a new isolated
        // process, starting another process if we are currently waiting
        // for a previous process to come up.  To deal with this, we store
        // in the service any current isolated process it is running in or
        // waiting to have come up.
        app = r.isolatedProc;
    }

    // Not running -- get it started, and enqueue this service record
    // to be executed when the app comes up.
    if (app == null) {
        // 建立一個新的程序
        if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
                "service", r.name, false, isolated, false)) == null) {
            String msg = "Unable to launch app "
                    + r.appInfo.packageName + "/"
                    + r.appInfo.uid + " for service "
                    + r.intent.getIntent() + ": process is bad";
            Slog.w(TAG, msg);
            // 如果啟動失敗則強制退出Service
            bringDownServiceLocked(r);
            return msg;
        }
        if (isolated) {
            r.isolatedProc = app;
        }
    }

    // mPendingServices用於儲存客戶程序請求啟動的ServiceRecord
    if (!mPendingServices.contains(r)) {
        mPendingServices.add(r);
    }

    if (r.delayedStop) {
        // Oh and hey we've already been asked to stop!
        r.delayedStop = false;
        if (r.startRequested) {
            if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
                    "Applying delayed stop (in bring up): " + r);
            stopServiceLocked(r);
        }
    }

    return null;
}


根據上面程式碼的分析,第一次建立一個Service時的流程是:

1.建立程序:startProcessLocked

2.第一次啟動Service:realStartServiceLocked

3.啟動已有的Service:sendServiceArgsLocked

下面安裝上面的流程講解:

1.ActivityManagerService類中的startProcessLocked方法建立了一個程序,這裡就不講解原始碼了,有興趣的可以看下。

2.ActiveServices類中的realStartServiceLocked方法:

private final void realStartServiceLocked(ServiceRecord r,
        ProcessRecord app, boolean execInFg) throws RemoteException {
    if (app.thread == null) {
        throw new RemoteException();
    }
    if (DEBUG_MU)
        Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
                + ", ProcessRecord.uid = " + app.uid);
    r.app = app;
    r.restartTime = r.lastActivity = SystemClock.uptimeMillis();

    // 在ActivityManagerService服務中記錄當前程序中執行的所有ServiceRecord
    final boolean newService = app.services.add(r);
    bumpServiceExecutingLocked(r, execInFg, "create");
    // mLruProcesses儲存系統最近執行的應用程式程序資訊,更新當前ProcessRecord在mLruProcesses中的狀態
    mAm.updateLruProcessLocked(app, false, null);
    mAm.updateOomAdjLocked();

    boolean created = false;
    try {
        if (LOG_SERVICE_START_STOP) {
            String nameTerm;
            int lastPeriod = r.shortName.lastIndexOf('.');
            nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
            EventLogTags.writeAmCreateService(
                    r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
        }
        synchronized (r.stats.getBatteryStats()) {
            r.stats.startLaunchedLocked();
        }
        // 檢查當前Service所在的包是否經過DexOpt優化過
        mAm.ensurePackageDexOpt(r.serviceInfo.packageName);
        app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
        // RPC呼叫ActivityThread類中的方法建立Service
        app.thread.scheduleCreateService(r, r.serviceInfo,
                mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
                app.repProcState);
        r.postNotification();
        created = true;
    } catch (DeadObjectException e) {
        Slog.w(TAG, "Application dead when creating service " + r);
        mAm.appDiedLocked(app);
        throw e;
    } finally {
        if (!created) {
            // Keep the executeNesting count accurate.
            final boolean inDestroying = mDestroyingServices.contains(r);
            serviceDoneExecutingLocked(r, inDestroying, inDestroying);

            // Cleanup.
            if (newService) {
                app.services.remove(r);
                r.app = null;
                if (SERVICE_RESCHEDULE && DEBUG_DELAYED_SERVICE) {
                Slog.w(TAG, " Failed to create Service !!!! ."
                       +"This will introduce huge delay...  "
                       +r.shortName + " in " + r.restartDelay + "ms");
                }
            }

            // Retry.
            if (!inDestroying) {
                scheduleServiceRestartLocked(r, false);
            }
        }
    }

    // 繫結該Service
    requestServiceBindingsLocked(r, execInFg);

    updateServiceClientActivitiesLocked(app, null, true);

    // If the service is in the started state, and there are no
    // pending arguments, then fake up one so its onStartCommand() will
    // be called.
    if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
        r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
                null, null));
    }

    // 啟動該Service
    sendServiceArgsLocked(r, execInFg, true);

    if (r.delayed) {
        if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
        getServiceMap(r.userId).mDelayedStartList.remove(r);
        r.delayed = false;
    }

    if (r.delayedStop) {
        // Oh and hey we've already been asked to stop!
        r.delayedStop = false;
        if (r.startRequested) {
            if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
                    "Applying delayed stop (from start): " + r);
            stopServiceLocked(r);
        }
    }
}


上面方法完成了Service的建立、繫結、啟動的呼叫。

真正的建立呼叫的是ActivityThread類中的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);
}


在上面方法中將呼叫引數資訊封裝為CreateServiceData物件,通過sendMessage方法嚮應用程式主執行緒MessageQueue中傳送一個CREATE_SERVICE訊息。

private class H extends Handler {
    
    . . .
    public static final int CREATE_SERVICE          = 114;
    . . .
    
    public void handleMessage(Message msg) {
        switch (msg.what) {
            . . .
            case CREATE_SERVICE:
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceCreate");
                handleCreateService((CreateServiceData)msg.obj);
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                break;
            . . .
        }
    }
}


H是ActivityThread的內部類,這裡又將Service的建立工作交給ActivityThread類的handleCreateService方法來完成:

private void handleCreateService(CreateServiceData data) {
    // If we are getting ready to gc after going to the background, well
    // we are back active so skip it.
    unscheduleGcIdler();

    LoadedApk packageInfo = getPackageInfoNoCheck(
            data.info.applicationInfo, data.compatInfo);
    Service service = null;
    try {
        java.lang.ClassLoader cl = packageInfo.getClassLoader();
        // data.info.name就是Service是類名,通過類載入器根據類名建立一個例項後強轉為Service類的例項
        service = (Service) cl.loadClass(data.info.name).newInstance();
    } catch (Exception e) {
        if (!mInstrumentation.onException(service, e)) {
            throw new RuntimeException(
                "Unable to instantiate service " + data.info.name
                + ": " + e.toString(), e);
        }
    }

    try {
        if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);

        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()方法
        service.onCreate();
        // mServices儲存了應用程式程序中所有的Service,把Service新增到該變數中
        mServices.put(data.token, service);
        try {
            // 通知ActivityManagerService,當前Service建立完成
            ActivityManagerNative.getDefault().serviceDoneExecuting(
                    data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
        } catch (RemoteException e) {
            // nothing to do.
        }
    } catch (Exception e) {
        if (!mInstrumentation.onException(service, e)) {
            throw new RuntimeException(
                "Unable to create service " + data.info.name
                + ": " + e.toString(), e);
        }
    }
}


這樣,Android系統建立服務的過程就分析完了。

3.ActiveServices類中的sendServiceArgsLocked方法:

private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
        boolean oomAdjusted) throws TransactionTooLargeException {
    final int N = r.pendingStarts.size();
    if (N == 0) {
        return;
    }

    // 遍歷Service啟動引數列表
    while (r.pendingStarts.size() > 0) {
        Exception caughtException = null;
        ServiceRecord.StartItem si;
        try {
            // 對引數列表中的每一項StartItem都啟動一次Service
            si = r.pendingStarts.remove(0);
            if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Sending arguments to: "
                    + r + " " + r.intent + " args=" + si.intent);
            if (si.intent == null && N > 1) {
                // If somehow we got a dummy null intent in the middle,
                // then skip it.  DO NOT skip a null intent when it is
                // the only one in the list -- this is to support the
                // onStartCommand(null) case.
                continue;
            }
            // 設定投遞時間
            si.deliveredTime = SystemClock.uptimeMillis();
            // 將已投遞引數項儲存到deliveredStarts列表中
            r.deliveredStarts.add(si);
            si.deliveryCount++;
            if (si.neededGrants != null) {
                mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
                        si.getUriPermissionsLocked());
            }
            bumpServiceExecutingLocked(r, execInFg, "start");
            if (!oomAdjusted) {
                oomAdjusted = true;
                mAm.updateOomAdjLocked(r.app);
            }
            int flags = 0;
            if (si.deliveryCount > 1) {
                flags |= Service.START_FLAG_RETRY;
            }
            if (si.doneExecutingCount > 0) {
                flags |= Service.START_FLAG_REDELIVERY;
            }
            // RPC呼叫ActivityThread類中的方法啟動Service
            r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
        } catch (TransactionTooLargeException e) {
            if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large: intent="
                    );
            caughtException = e;
        } catch (RemoteException e) {
            // Remote process gone...  we'll let the normal cleanup take care of this.
            if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
            caughtException = e;
        } catch (Exception e) {
            Slog.w(TAG, "Unexpected exception", e);
            caughtException = e;
        }

        if (caughtException != null) {
            // Keep nesting count correct
            final boolean inDestroying = mDestroyingServices.contains(r);
            serviceDoneExecutingLocked(r, inDestroying, inDestroying);
            if (caughtException instanceof TransactionTooLargeException) {
                throw (TransactionTooLargeException)caughtException;
            }
            break;
        }
    }
}


ActivityThread類中的scheduleServiceArgs方法:

public final void scheduleServiceArgs(IBinder token, boolean taskRemoved,
        int startId, int flags, Intent args) {
    ServiceArgsData s = new ServiceArgsData();
    s.token = token;
    s.taskRemoved = taskRemoved;
    s.startId = startId;
    s.flags = flags;
    s.args = args;

    sendMessage(H.SERVICE_ARGS, s);
}

private class H extends Handler {
    . . .
    public static final int SERVICE_ARGS            = 115;
    . . .

    public void handleMessage(Message msg) {
        switch (msg.what) {
            . . .
            case SERVICE_ARGS:
                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStart");
                handleServiceArgs((ServiceArgsData)msg.obj);
                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                break;
            . . .
        }
    }

}


這裡又將呼叫ActivityThread類的handleServiceArgs方法來啟動服務:

private void handleServiceArgs(ServiceArgsData data) {
    Service s = mServices.get(data.token);
    if (s != null) {
        try {
            if (data.args != null) {
                data.args.setExtrasClassLoader(s.getClassLoader());
                data.args.prepareToEnterProcess();
            }
            int res;
            if (!data.taskRemoved) {
                // 回撥Service的onStartCommand方法
                res = s.onStartCommand(data.args, data.flags, data.startId);
            } else {
                s.onTaskRemoved(data.args);
                res = Service.START_TASK_REMOVED_COMPLETE;
            }

            QueuedWork.waitToFinish();

            try {
                // 通知ActivityManagerService,Service啟動完成
                ActivityManagerNative.getDefault().serviceDoneExecuting(
                        data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
            } catch (RemoteException e) {
                // nothing to do.
            }
            ensureJitEnabled();
        } catch (Exception e) {
            if (!mInstrumentation.onException(s, e)) {
                throw new RuntimeException(
                        "Unable to start service " + s
                        + " with " + data.args + ": " + e.toString(), e);
            }
        }
    }
}


這樣,Service的啟動過程也分析完了。