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

Android 源碼解析(十一):應用進程的啟動流程

編輯:關於 Android 程式設計

Android 官方 guide 中有這樣一段描述:

By default, every application runs in its own Linux process. Android starts the process when any of the application's components need to be executed, then shuts down the process when it's no longer needed or when the system must recover memory for other applications.

也就是說,每個 Android 應用默認運行在獨立的 Linux 進程中。系統在該應用的某個組件需要執行時啟動進程,並在沒有組件運行、或需要為其他應用回收內存時結束它。因此,當我們要啟動四大組件之一,而宿主進程尚未啟動時,系統會先把進程拉起來。

本文以 Activity 的啟動過程為切入點,梳理應用進程的啟動流程。

從點擊桌面圖標說起

上一篇文章介紹過:SystemServer 完成各項系統服務啟動後,會調用 ActivityManagerService 的 systemReady(),Launcher 的啟動邏輯就在其中。Launcher 啟動時會向 PackageManagerService 查詢系統中所有已安裝應用的包名、圖標與名稱,填充到自己的 Adapter 中。於是我們點擊某個圖標時,就能根據它的包名和啟動 Activity 類名構造 Intent,調用 startActivity(Intent)。

事實上,啟動 Activity、Service、ContentProvider 或 BroadcastReceiver 都可能導致進程被拉起。系統會先判斷該組件所屬進程是否存在,不存在則先創建進程。

Launcher 的圖標點擊事件:

protected void onListItemClick(ListView l, View v, int position, long id) {
    Intent intent = intentForPosition(position);
    startActivity(intent);
}

關鍵在於:此刻應用進程還沒啟動,而 startActivity 卻成功打開了 Activity——說明它在啟動 Activity 之前,先把進程拉起來了。下面就以這個方法為入口跟蹤。

一層層往下追

Activity 中的重載調用:

@Override
public void startActivity(Intent intent) {
    this.startActivity(intent, null);
}

@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        startActivityForResult(intent, -1, options);
    } else {
        startActivityForResult(intent, -1);
    }
}

public void startActivityForResult(Intent intent, int requestCode) {
    startActivityForResult(intent, requestCode, null);
}

最終落到核心重載:

public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {
    if (mParent == null) {
        Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
        if (ar != null) {
            mMainThread.sendActivityResult(mToken, mEmbeddedID, requestCode,
                    ar.getResultCode(), ar.getResultData());
        }
        ...
    } else {
        mParent.startActivityFromChild(this, intent, requestCode, options);
    }
}

這裡出現了 Instrumentation。它是 Android 應用端操作 Activity 的具體代理類(相對於 ActivityManagerService 這個服務端而言),Activity 生命周期的實際調度都經由它完成。

public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token,
        Activity target, Intent intent, int requestCode, Bundle options) {
    ...
    int result = ActivityManagerNative.getDefault()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()),
                    token, target != null ? target.mEmbeddedID : null,
                    requestCode, 0, null, options);
    checkStartActivityResult(result, intent);
    ...
}

跨進程:交給 AMS

ActivityManagerNative 繼承自 Binder 接口,是 Binder 機制的客戶端;而 ActivityManagerService 繼承自 ActivityManagerNative,是服務端。所以上面這行本質是一次跨進程通訊——把參數傳給 AMS 並執行它的 startActivity。

// ActivityManagerService
@Override
public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
        String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle options) {
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, options,
            UserHandle.getCallingUserId());
}

@Override
public final int startActivityAsUser(..., int userId) {
    enforceNotIsolatedCaller("startActivity");
    userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
            false, ALLOW_FULL_ONLY, "startActivity", null);
    return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
            resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
            profilerInfo, null, null, options, false, userId, null, null);
}

ActivityStackSupervisor 的接力

接下來是一串層層調用,把 Activity 一路推向啟動:

// ActivityStackSupervisor
final int startActivityMayWait(...) {
    int res = startActivityLocked(caller, intent, resolvedType, aInfo, ...);
    return res;
}

final int startActivityLocked(...) {
    err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
            startFlags, true, options, inTask);
    ...
}

final int startActivityUncheckedLocked(...) {
    targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
    ...
}

// ActivityStack
final void startActivityLocked(ActivityRecord r, boolean newTask, ...) {
    ...
    if (doResume) {
        mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
    }
}

// ActivityStackSupervisor
boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target, ...) {
    stack.resumeTopActivityLocked(null);
    ...
}

final boolean resumeTopActivityLocked(ActivityRecord prev) {
    return resumeTopActivityLocked(prev, null);
}

final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
    result = resumeTopActivityInnerLocked(prev, options);
    ...
}

final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
    mStackSupervisor.startSpecificActivityLocked(next, true, true);
    ...
}

真正啟動進程的地方

// ActivityStackSupervisor
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
    ...
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
            "activity", r.intent.getComponent(), false, false, true);
}

// ActivityManagerService
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
        boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
        boolean allowWhileBooting, boolean isolated, boolean keepIfLarge) {
    return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType,
            hostingName, allowWhileBooting, 0, keepIfLarge, null, null, null, null, null);
}

final ProcessRecord startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr,
        String abiOverride, String entryPoint, String[] entryPointArgs) {
    ...
    startProcessLocked(app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs);
    ...
}

// 最終通過 Process.start 請求 zygote
Process.ProcessStartResult startResult = Process.start(entryPoint, app.processName,
        uid, uid, gids, debugFlags, mountExternal, app.info.targetSdkVersion,
        app.info.seinfo, requiredAbi, instructionSet, app.info.dataDir, entryPointArgs);
// android.os.Process
public static final ProcessStartResult start(final String processClass, final String niceName,
        int uid, int gid, int[] gids, int debugFlags, int mountExternal,
        int targetSdkVersion, String seInfo, String abi, String instructionSet,
        String appDataDir, String[] zygoteArgs) {
    try {
        return startViaZygote(processClass, niceName, uid, gid, gids, debugFlags,
                mountExternal, targetSdkVersion, seInfo, abi, instructionSet,
                appDataDir, zygoteArgs);
    } catch (ZygoteStartFailedEx ex) {
        throw new RuntimeException("Starting VM process through Zygote failed", ex);
    }
}

這裡的 processClass 就是待啟動進程的入口類,傳入的是:

"android.app.ActivityThread"

Process 啟動進程的 Native 層實現本文不做展開。要點是:這個方法讓 zygote fork 出新的進程,並執行 ActivityThread 的 main 方法——這也就是我們常說的「進程入口是 ActivityThread.main」的由來。

小結

  • Android 應用在需要啟動其組件時才會啟動進程;沒有組件運行或系統內存緊張時,進程會被回收。
  • 啟動四大組件時若發現進程不存在,系統會先創建進程,再啟動組件。
  • 可以為應用配置多個進程,每個進程擁有獨立的 VM 與運行環境,進程間通信依賴 Binder 機制。
  • Launcher 自身也是先啟動進程,再啟動其 Activity 組件。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved