Activity 與 ActivityManagerService 的啓動過程

參考資料:
Android 8.0 ActivityManagerService 啓動流程
Android四大組件之Activity–管理方式(這個博主寫的其他文章都很不錯,推薦也都去看一看)
基於Android 9.0的Activity啓動流程源碼分析

SDK 版本:29.0.2

從 Android 的啓動流程開始講起。

Android 設備啓動要經歷三個階段,Boot Loader、Linux Kernel 和 Android 系統服務,而第一個啓動的進程是 init 進程,然後由 init 進程創建出其他進程(其中就有 Zygote 進程)。ServiceManager 進程用於 Binder 機制,這裏不過多提及。 ActivityManagerService 是寄存在 SystemServer 中的,它會在系統啓動時創建一個線程來進行工作。而 SystemServer 由 Zygote 進程創建(Android 的大多數應用進程和系統進程都是由它來創建的),而入口就是 ZygoteInit 的 main 函數:

/*ZygoteInit*/
@UnsupportedAppUsage
public static void main(String argv[]) {
    ...
    try {
    	...
    	if (startSystemServer) {
            Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);

            // {@code r == null} in the parent (zygote) process, and {@code r != null} in the
            // child (system_server) process.
            if (r != null) {
                r.run();
                return;
            }
        }
        ...
    }
    ...
}
private static Runnable forkSystemServer(String abiList, String socketName,
        ZygoteServer zygoteServer) {
    ...
    try {
    	...
    	/* Request to fork the system server process */
    	pid = Zygote.forkSystemServer(
                parsedArgs.mUid, parsedArgs.mGid,
                parsedArgs.mGids,
                parsedArgs.mRuntimeFlags,
                null,
                parsedArgs.mPermittedCapabilities,
                parsedArgs.mEffectiveCapabilities);
    }
    ...
    /* For child process (也就是 SystemServer 進程)*/
    if (pid == 0) {
        if (hasSecondZygote(abiList)) {
            waitForSecondaryZygote(socketName);
        }

        zygoteServer.closeServerSocket();
        return handleSystemServerProcess(parsedArgs);	//啓動各種支撐系統運行的Sytem Server
    }

    return null;
}

/*Zygote*/
public static int forkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
        int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
    ...
	int pid = nativeForkSystemServer(
            uid, gid, gids, runtimeFlags, rlimits,
            permittedCapabilities, effectiveCapabilities);
    ...
}
private static native int nativeForkSystemServer(int uid, int gid, int[] gids, int runtimeFlags,
        int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);

Zygote 進程調用了 native 的方法 fork 了 SystemServer 進程,上面的步驟瞭解就行,重點放在 ActivityManagerService^{①} 代碼即可,由於 SystemServer 在新進程中,接下來就看 SystemServer 的 main 函數:

/*SystemServer*/
/**
 * The main entry point from zygote.
 */
public static void main(String[] args) {
    new SystemServer().run();
}
private void run() {
	...
	// Start services.
    try {
        ...
        startBootstrapServices();		//系統引導服務
        ...
    }
    ...
}
private void startBootstrapServices() {
	...
	mActivityManagerService = ActivityManagerService.Lifecycle.startService(
            mSystemServiceManager, atm);
    ...
}

/*ActivityManagerService.Lifecycle*/
public static final class Lifecycle extends SystemService {
	private final ActivityManagerService mService;
    private static ActivityTaskManagerService sAtm;

    public Lifecycle(Context context) {
        super(context);
        mService = new ActivityManagerService(context, sAtm);
    }
    public static ActivityManagerService startService(
            SystemServiceManager ssm, ActivityTaskManagerService atm) {
        sAtm = atm;
        return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
    }
    ...
    public ActivityManagerService getService() {
        return mService;
    }
}

/*SystemServiceManager*/
/*
 * Creates and starts a system service. The class must be a subclass of
 * 這裏通過反射的方法獲得了 Lifecycle 實例
 */
@SuppressWarnings("unchecked")
public <T extends SystemService> T startService(Class<T> serviceClass) {
    try {
        ...
        try {
            Constructor<T> constructor = serviceClass.getConstructor(Context.class);
            service = constructor.newInstance(mContext);
        }
        ...
        startService(service);
        return service;
    }
    ...
}

它通過 SystemServiceManager 獲得了 Lifecycle 實例,再調用 getService 方法獲取到了 ActivityManagerService 實例,這樣 SystemServer 就持有了這個實例。

不過 ActivityManagerService 還沒有啓動起來,再看 startService 方法,它調用的是 SystemService 的抽象方法 onStart,ActivityManagerService.Lifecycle 繼承於它。

/*SystemServiceManager*/
public void startService(@NonNull final SystemService service) {
    ...
    // Start it.
    ...
    try {
        service.onStart();
    }
    ...
}

/*ActivityManagerService.Lifecycle*/
public static final class Lifecycle extends SystemService {
    private final ActivityManagerService mService;
    ...
    @Override
    public void onStart() {
        mService.start();
    }
    ...
}

/*ActivityManagerService*/
private void start() {
    removeAllProcessGroups();
    mProcessCpuThread.start();
    mBatteryStatsService.publish();
    mAppOpsService.publish(mContext);
    Slog.d("AppOps", "AppOpsService published");
    LocalServices.addService(ActivityManagerInternal.class, new LocalService());
    mActivityTaskManager.onActivityManagerInternalAdded();
    mUgmInternal.onActivityManagerInternalAdded();
    mPendingIntentController.onActivityManagerInternalAdded();
    // Wait for the synchronized block started in mProcessCpuThread,
    // so that any other access to mProcessCpuTracker from main thread
    // will be blocked during mProcessCpuTracker initialization.
    try {
        mProcessCpuInitLatch.await();
    } catch (InterruptedException e) {
        Slog.wtf(TAG, "Interrupted wait during start", e);
        Thread.currentThread().interrupt();
        throw new IllegalStateException("Interrupted wait during start");
    } 
}

這樣 ActivityManagerService 就算是啓動起來了(ActivityManagerService 還在 startBootstrapServices 方法中進行了一系列的設置,這裏就不一一列舉出來了)。

ActivityManagerService 持有一個叫做 ActivityTaskManagerService 的類,它的描述是這樣的:

System service for managing activities and their containers (task, stacks, displays,... ).
用於管理 activities 及其容器(任務,堆棧,屏幕顯示等)的系統服務。

然後 ActivityManagerService 還持有這一個對象,剛纔調用 ActivityManagerService 構造方法的時候,就開始創建 ActivityTaskManagerService。

@VisibleForTesting
public ActivityTaskManagerService mActivityTaskManager;

// Note: This method is invoked on the main thread but may need to attach various
// handlers to other threads.  So take care to be explicit about the looper.
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
	...
	mActivityTaskManager = atm;
	...
}

ActivityTaskManagerService 從何而來?我們回想一下,這個構造方法是在 ActivityManagerService.Lifecycle 的 startService 方法中調用的,而它又是從 SytemServer 的 startBootstrapServices 調用的,往回一找,看到:

ActivityTaskManagerService atm = mSystemServiceManager.startService(
            ActivityTaskManagerService.Lifecycle.class).getService();

這個傢伙也是使用相同的方法創建的,繼續跟進:

/*SystemServiceManager*/
@SuppressWarnings("unchecked")
public <T extends SystemService> T startService(Class<T> serviceClass) {
    try {
        ...
        try {
            Constructor<T> constructor = serviceClass.getConstructor(Context.class);
            service = constructor.newInstance(mContext);
        }
        ...
        startService(service);
        return service;
    }
    ...
}

/*ActivityTaskManagerService.Lifecycle*/
public static final class Lifecycle extends SystemService {
    private final ActivityTaskManagerService mService;

    public Lifecycle(Context context) {
        super(context);
        mService = new ActivityTaskManagerService(context);
    }
	...
    public ActivityTaskManagerService getService() {
        return mService;
    }
}

ActivityManagerService 就獲取到了 ActivityTaskManagerService 實例。

我們回到 SystemServer 類的 run 方法再接着往下看:

private void run() {
	...
	// Start services.
    try {
        ...
        startBootstrapServices();		//系統引導服務
        startCoreServices();			//核心服務
        startOtherServices();			//其他服務
        ...
    }
    ...
}

不用關心核心服務,就看其他服務:

/*SystemServer*/
/**
 * Starts a miscellaneous grab bag of stuff that has yet to be refactored and organized.
 */
private void startOtherServices() {
    ...
    // We now tell the activity manager it is okay to run third party
    // code.  It will call back into us once it has gotten to the state
    // where third party code can really run (but before it has actually
    // started launching the initial applications), for us to complete our
    // initialization.
    // 這段話我翻不了,google 翻譯的不太通順,順便貼一下
    // 現在,我們告訴活動管理器可以運行第三方代碼。 一旦到達了可以真正運行第三方代碼的狀態
    // (但實際上尚未啓動初始應用程序之前),它將回叫我們,以便我們完成初始化。
    mActivityManagerService.systemReady(() -> {
        ...
    }, BOOT_TIMINGS_TRACE_LOG);
}

/*ActivityManagerService*/
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
    traceLog.traceBegin("PhaseActivityManagerReady");
    synchronized(this) {
        if (mSystemReady) {
            // If we're done calling all the receivers, run the next "boot phase" passed in
            // by the SystemServer
            if (goingCallback != null) {
                goingCallback.run();
            }
            return;
        }
        ...
    }
    ...
    synchronized (this) {
    	...
    	mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
    	...
    }
}
@VisibleForTesting
public ActivityTaskManagerInternal mAtmInternal;

它調用了 ActivityTaskManagerInternal 的 startHomeOnAllDisplays 方法要啓動桌面了。不過 ActivityTaskManagerInternal 可是一個抽象類,ActivityManagerService.LocalService 繼承了它。並且它調用的是 RootActivityContainer.startHomeOnAllDisplays。

/*ActivityTaskManagerInternal*/
/**
 * Activity Task manager local system service interface.
 */
public abstract class ActivityTaskManagerInternal {
	...
}

/*ActivityManagerService.LocalService*/
final class LocalService extends ActivityTaskManagerInternal {
	...
	@Override
    public boolean startHomeOnAllDisplays(int userId, String reason) {
        synchronized (mGlobalLock) {
            return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
        }
    }
	...
}

/*RootActivityContainer*/
boolean startHomeOnAllDisplays(int userId, String reason) {
    boolean homeStarted = false;
    for (int i = mActivityDisplays.size() - 1; i >= 0; i--) {
        final int displayId = mActivityDisplays.get(i).mDisplayId;
        homeStarted |= startHomeOnDisplay(userId, reason, displayId);
    }
    return homeStarted;
}

RootActivityContainer 的定義是:

Root node for activity containers.
activity 容器的根節點。

它通過 ActivityTaskManagerService 構造來的:

/*RootActivityContainer*/
RootActivityContainer(ActivityTaskManagerService service) {
    mService = service;
    mStackSupervisor = service.mStackSupervisor;
    mStackSupervisor.mRootActivityContainer = this;
}

/*ActivityTaskManagerService*/
public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController, Looper looper) {
	...
	mRootActivityContainer = new RootActivityContainer(this);
	...
}

/*ActivityManagerService*/
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
	...
	mActivityTaskManager = atm;
    mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
            DisplayThread.get().getLooper());
	...
}

在創建 ActivityManagerService 的時候,RootActivityContainer 就被創建了。

mActivityDisplays 變量是:

/**
 * List of displays which contain activities, sorted by z-order.
 * The last entry in the list is the topmost.
 * 包含 activity 的顯示列表,按 z-order 排序。列表中的最後一個條目是在最上面的。
 */
private final ArrayList<ActivityDisplay> mActivityDisplays = new ArrayList<>();

那 ActivityDisplay 是?

/**
 * Exactly one of these classes per Display in the system. Capable of holding zero or
 * more attached {@link ActivityStack}s.
 */
 每一個物理屏幕對應着一個實例,能夠容納零個或多個 ActivityStacks。

因爲 Android 是支持多屏顯示的,而 mActivityDisplays 就存着物理屏幕上的 ActivityStack。ActivityStack 又包含 TaskStack,TaskStack 又包含 ActivityRecord。

搬運工來了,以下文字和圖片來自開頭給的資料鏈接:

在這裏插入圖片描述

圖中的方框可以理解爲一箇中包含關係:譬如一個 TaskRecord 中包含多個 ActivityRecord ; 圖中的連接線可以理解爲等價關係,譬如同一個 ActivityRecord 會被 TaskRecord 和 ProcessRecord 引用,兩者是從不同維度來管理 ActivityRecord 。

  • ActivityRecord 是 Activity 管理的最小單位,它對應着一個用戶界面,是 AMS調度 Activity的基本單位。
  • TaskRecord 是一個棧式管理結構,每一個 TaskRecord 都可能存在一個或多個 ActivityRecord,棧頂的ActivityRecord 表示當前可見的界面。啓動 Activity時,需要找到 Activity的宿主任務,如果不存在,則需要新建一個,也就是說所有的 ActivityRecord都必須有宿主。
  • ActivityStack 是一個棧式管理結構,每一個 ActivityStack 都可能存在一個或多個 TaskRecord,棧頂的TaskRecord 表示當前可見的任務。
  • ActivityStackSupervisor 管理着多個 ActivityStack,但當前只會有一個獲取焦點 (Focused)的 ActivityStack。
  • ProcessRecord 記錄着屬於一個進程的所有 ActivityRecord,運行在不同 TaskRecord 中的 ActivityRecord 可能是屬於同一個 ProcessRecord。AMS採用 ProcessRecord 這個數據結構來維護進程運行時的狀態信息,當創建系統進程 (system_process) 或應用進程的時候,就會通過 AMS初始化一個 ProcessRecord。

不過上面的文章是 16 年的,目前可能會有些改動,但不妨礙我們理解它的機制。接下來繼續跟進(我這個英語渣就不翻譯下面這些註釋了):

/*RootActivityContainer*/
boolean startHomeOnDisplay(int userId, String reason, int displayId) {
    return startHomeOnDisplay(userId, reason, displayId, false /* allowInstrumenting */,
            false /* fromHomeKey */);
}

/**
 * This starts home activity on displays that can have system decorations based on 
 * displayId -
 * Default display always use primary home component.
 * For Secondary displays, the home activity must have category SECONDARY_HOME and then 
 * resolves according to the priorities listed below.
 *  - If default home is not set, always use the secondary home defined in the config.
 *  - Use currently selected primary home activity.
 *  - Use the activity in the same package as currently selected primary home activity.
 *    If there are multiple activities matched, use first one.
 *  - Use the secondary home defined in the config.
 */
boolean startHomeOnDisplay(int userId, String reason, int displayId, 
        boolean allowInstrumenting, boolean fromHomeKey) {
    // Fallback to top focused display if the displayId is invalid.
    if (displayId == INVALID_DISPLAY) {
        displayId = getTopDisplayFocusedStack().mDisplayId;
    }
    Intent homeIntent = null;
    ActivityInfo aInfo = null;
    if (displayId == DEFAULT_DISPLAY) {
        homeIntent = mService.getHomeIntent();
        aInfo = resolveHomeActivity(userId, homeIntent);
    } else if (shouldPlaceSecondaryHomeOnDisplay(displayId)) {
        Pair<ActivityInfo, Intent> info = resolveSecondaryHomeActivity(userId, displayId);
        aInfo = info.first;
        homeIntent = info.second;
    }
    if (aInfo == null || homeIntent == null) {
        return false;
    }

    if (!canStartHomeOnDisplay(aInfo, displayId, allowInstrumenting)) {
        return false;
    }

    // Updates the home component of the intent.
    homeIntent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
    homeIntent.setFlags(homeIntent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
    // Updates the extra information of the intent.
    if (fromHomeKey) {
        homeIntent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, true);
    }
    // Update the reason for ANR debugging to verify if the user activity is the one that
    // actually launched.
    final String myReason = reason + ":" + userId + ":" + UserHandle.getUserId(
            aInfo.applicationInfo.uid) + ":" + displayId;
    mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason,
            displayId);
    return true;
}

/*ActivityTaskManagerService*/
Intent getHomeIntent() {
    Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
    intent.setComponent(mTopComponent);
    intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
    if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
        intent.addCategory(Intent.CATEGORY_HOME);
    }
    return intent;
}

/**
 * The default Display id, which is the id of the built-in primary display
 * assuming there is one.
 * 默認 Display ID,即假設有一個內置主 Display ID。(我可以理解爲是手機屏幕)
 */
public static final int DEFAULT_DISPLAY = 0;

看到了嗎,獲取了一個叫 homeIntent 的實例,然後調用了 startHomeActivity,在此之前先看看它前面都是什麼:

ActivityTaskManagerService mService;

/*ActivityTaskManagerService*/
ActivityStartController getActivityStartController() {
    return mActivityStartController;
}
private ActivityStartController mActivityStartController;
public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController, Looper looper) {
	...
	mRootActivityContainer = new RootActivityContainer(this);
	...
	mActivityStartController = new ActivityStartController(this);
	...
}

/*ActivityStartController*/
void startHomeActivity(Intent intent, ActivityInfo aInfo, String reason, int displayId) {
	...
	mLastHomeActivityStartResult = obtainStarter(intent, "startHomeActivity: " + reason)
            .setOutActivity(tmpOutRecord)
            .setCallingUid(0)
            .setActivityInfo(aInfo)
            .setActivityOptions(options.toBundle())
            .execute();
    ...
}
/**
 * @return A starter to configure and execute starting an activity. It is valid until after
 * {@link ActivityStarter#execute} is invoked. At that point, the starter should be
 * considered invalid and no longer modified or used.
 */
ActivityStarter obtainStarter(Intent intent, String reason) {
    return mFactory.obtain().setIntent(intent).setReason(reason);
}

private final Factory mFactory

Factory 從哪來?

/*ActivityStartController*/
ActivityStartController(ActivityTaskManagerService service) {
    this(service, service.mStackSupervisor,
        new DefaultFactory(service, service.mStackSupervisor,
            new ActivityStartInterceptor(service, service.mStackSupervisor)));
}
@VisibleForTesting
ActivityStartController(ActivityTaskManagerService service, ActivityStackSupervisor supervisor,
        Factory factory) {
    mService = service;
    mSupervisor = supervisor;
    mHandler = new StartHandler(mService.mH.getLooper());
    mFactory = factory;
    mFactory.setController(this);
    mPendingRemoteAnimationRegistry = new PendingRemoteAnimationRegistry(service,
            service.mH);
}

/*ActivityStarter.DefaultFactory*/
static class DefaultFactory implements Factory {
    ...
    DefaultFactory(ActivityTaskManagerService service,
            ActivityStackSupervisor supervisor, ActivityStartInterceptor interceptor) {
        mService = service;
        mSupervisor = supervisor;
        mInterceptor = interceptor;
    }
    ...
    @Override
    public ActivityStarter obtain() {
        ActivityStarter starter = mStarterPool.acquire();	//SynchronizedPool

        if (starter == null) {
            starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
        }
        return starter;
    }
    ...
}

/*ActivityStarter*/
ActivityStarter(ActivityStartController controller, ActivityTaskManagerService service,
        ActivityStackSupervisor supervisor, ActivityStartInterceptor interceptor) {
    mController = controller;
    mService = service;
    mRootActivityContainer = service.mRootActivityContainer;
    mSupervisor = supervisor;
    mInterceptor = interceptor;
    reset(true);
}

先來看新來的這兩個類:

/**
 * Controller for delegating activity launches.
 * 委派 activity 啓動的控制器。
 * This class' main objective is to take external activity start requests and prepare them into
 * a series of discrete activity launches that can be handled by an {@link ActivityStarter}. It is
 * also responsible for handling logic that happens around an activity launch, but doesn't
 * necessarily influence the activity start. Examples include power hint management, processing
 * through the pending activity list, and recording home activity launches.
 */
public class ActivityStartController
 
 /**
 * Controller for interpreting how and then launching an activity.
 * 就是啓動 activity 的控制器
 * This class collects all the logic for determining how an intent and flags should be turned into
 * an activity and associated task and stack.
 */
class ActivityStarter

再接着往下看:

/**
 * Starts an activity based on the request parameters provided earlier.
 * @return The starter result.
 * 根據之前提供的請求參數 activity 活動。
 */
int execute() {
   try {
        // TODO(b/64750076): Look into passing request directly to these methods to allow
        // for transactional diffs and preprocessing.
        if (mRequest.mayWait) {
            return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                    mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
                    mRequest.intent, mRequest.resolvedType,
                    mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                    mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
                    mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
                    mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
                    mRequest.inTask, mRequest.reason,
                    mRequest.allowPendingRemoteAnimationRegistryLookup,
                    mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
        } else {
            return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
                    mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
                    mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
                    mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
                    mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
                    mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
                    mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
                    mRequest.outActivity, mRequest.inTask, mRequest.reason,
                    mRequest.allowPendingRemoteAnimationRegistryLookup,
                    mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
        }
    } finally {
        onExecutionComplete();
    }
}

通過 ActivityStarter 類啓動了 HomeActivity。個人能力有限,我就不往下分析了。啓動完桌面以後就要從桌面啓動 app 了。由於桌面也是一個 Activity,那麼我們就把問題看做 Activity 啓動 Activity 即可。我們來看 Activity 的 startActivity 方法:

@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 {
        // Note we want to go through this call for compatibility with
        // applications that may have overridden the method.
        startActivityForResult(intent, -1);
    }
}

startActivity 調用了 startActivityForResult:

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
    startActivityForResult(intent, requestCode, null);
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
            @Nullable Bundle options) {
    if (mParent == null) {
        options = transferSpringboardActivityOptions(options);
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
        ...
    } else {
        if (options != null) {
            mParent.startActivityFromChild(this, intent, requestCode, options);
        } else {
            // Note we want to go through this method for compatibility with
            // existing applications that may have overridden it.
            mParent.startActivityFromChild(this, intent, requestCode);
        }
    }
}
public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
        int requestCode) {
    startActivityFromChild(child, intent, requestCode, null);
}
public void startActivityFromChild(@NonNull Activity child, @RequiresPermission Intent intent,
        int requestCode, @Nullable Bundle options) {
    options = transferSpringboardActivityOptions(options);
    Instrumentation.ActivityResult ar =
        mInstrumentation.execStartActivity(
            this, mMainThread.getApplicationThread(), mToken, child,
            intent, requestCode, options);
    if (ar != null) {
        mMainThread.sendActivityResult(
            mToken, child.mEmbeddedID, requestCode,
            ar.getResultCode(), ar.getResultData());
    }
    cancelInputsAndStartExitTransition(options);
}

mParent 變量是 Activity 類型,都調用的是 Instrumentation.execStartActivity 方法。Instrumentation 是啥?

/**
 * Base class for implementing application instrumentation code.  When running
 * with instrumentation turned on, this class will be instantiated for you
 * before any of the application code, allowing you to monitor all of the
 * interaction the system has with the application.  An Instrumentation
 * implementation is described to the system through an AndroidManifest.xml's
 * <instrumentation> tag.
 */
Instrumentation 提供了一種允許用戶獲取(及改變)應用程序與系統之間的交互流程的機制。
而自動化測試框架可以看成是這種機制的一種典型的應用形式,但絕不是全部。
(來自深入理解 Android 內核設計思想 Instrumentation 小節)

其強大的跟蹤 application 及 activity 生命週期的功能,一般用於 android 應用測試框架中,這裏不過多提及。

/*Activity*/
@UnsupportedAppUsage
private Instrumentation mInstrumentation;
@UnsupportedAppUsage
final void attach(Context context, ActivityThread aThread,
        Instrumentation instr, IBinder token, int ident,
        Application application, Intent intent, ActivityInfo info,
        CharSequence title, Activity parent, String id,
        NonConfigurationInstances lastNonConfigurationInstances,
        Configuration config, String referrer, IVoiceInteractor voiceInteractor,
        Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
    ...
    mInstrumentation = instr;
    ...
}

/*ActivityThread*/
/**  Core implementation of activity launch. */
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
	...
	try {
        ...
        if (activity != null) {
            ...
            activity.attach(appContext, this, getInstrumentation(), r.token,
                    r.ident, app, r.intent, r.activityInfo, title, r.parent,
                    r.embeddedID, r.lastNonConfigurationInstances, config,
                    r.referrer, r.voiceInteractor, window, r.configCallback,
                    r.assistToken);
            ...
        }
        ...
    }
	...
}
@UnsupportedAppUsage
public Instrumentation getInstrumentation()
{
    return mInstrumentation;
}
@UnsupportedAppUsage
Instrumentation mInstrumentation;

好了,再接着往下深♂入:

/*Instrumentation*/
@UnsupportedAppUsage
public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
    ...
    try {
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess(who);
        int result = ActivityTaskManager.getService()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()),
                    token, target != null ? target.mEmbeddedID : null,
                    requestCode, 0, null, options);
        checkStartActivityResult(result, intent);		//這裏大家可以去看看,平時啓動 Activity 拋的異常就在裏面
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}

/*ActivityTaskManager*/
public static IActivityTaskManager getService() {
    return IActivityTaskManagerSingleton.get();
}
@UnsupportedAppUsage(trackingBug = 129726065)
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
        new Singleton<IActivityTaskManager>() {
            @Override
            protected IActivityTaskManager create() {
                final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
                return IActivityTaskManager.Stub.asInterface(b);
            }
        };
        
/*Singleton*/    
/**
 * Singleton helper class for lazily initialization.
 * Modeled after frameworks/base/include/utils/Singleton.h
 */
public abstract class Singleton<T> {
    @UnsupportedAppUsage
    private T mInstance;

    protected abstract T create();

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

IActivityTaskManager.Stub.asInterface(b) 是通過 AIDL 生成了 IActivityManager (這裏也是沒有源碼,跟蹤不了)並且返回實現類 ActivityManagerService。跟蹤它的 startActivity 方法:

@Override
public int startActivity(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
    return mActivityTaskManager.startActivity(caller, callingPackage, intent, resolvedType,
            resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions);
}

mActivityTaskManager 之前說過是 ActivityTaskManagerService 的引用,如果忘了從哪獲取的回去看一下。

@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, bOptions,
            UserHandle.getCallingUserId());
}
@Override
public int startActivityAsUser(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
            true /*validateIncomingUser*/);
}
int startActivityAsUser(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
        boolean validateIncomingUser) {
    enforceNotIsolatedCaller("startActivityAsUser");

    userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
            Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
    // TODO: Switch to user app stacks here.
    return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
            .setCaller(caller)
            .setCallingPackage(callingPackage)
            .setResolvedType(resolvedType)
            .setResultTo(resultTo)
            .setResultWho(resultWho)
            .setRequestCode(requestCode)
            .setStartFlags(startFlags)
            .setProfilerInfo(profilerInfo)
            .setActivityOptions(bOptions)
            .setMayWait(userId)
            .execute();
}
ActivityStartController getActivityStartController() {
    return mActivityStartController;
}

這就和前面講啓動 homeActivity 一樣,ActivityManagerService 和 Activity 創建流程就算是過了一遍。(文章開頭給的第三篇文章他往下分析了,感興趣的可以繼續跟進)

註釋:
① ActivityManagerService 實際上不僅僅管理 Activity,四大組件都是由它來管理的。組件狀態的管理和查詢, Task ,電池信息狀態,權限管理服務以及提供了系統運行時信息查詢的輔助功能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章