AMS-Activity啟動(dòng)流程

本文基于Android_9.0湿颅、kernel_3.18源碼

PMS-PackageManagerService我們知道,PMS會(huì)在開(kāi)機(jī)/安裝app時(shí)解析APK的AndroidManifest.xml文件,并將解析的結(jié)果緩存在PMS中置侍。

接下來(lái)分析啟動(dòng)Activity的流程。

Launcher啟動(dòng)流程

Launcher啟動(dòng)流程.jpg

一晤柄、AMS獲取Launcher的Activity

1、SystemServer

Binder(五)服務(wù)注冊(cè)流程-發(fā)送注冊(cè)請(qǐng)求可知:
手機(jī)開(kāi)機(jī)后會(huì)啟動(dòng)system_server進(jìn)程妖胀,然后調(diào)用SystemServer的main方法芥颈,在main方法中通過(guò)startBootstrapServices啟動(dòng)AMS。之后通過(guò)startOtherServices方法調(diào)用AMS的systemReady 赚抡,告知AMS可以執(zhí)行第三方代碼爬坑。

private void startBootstrapServices() {
    ...
    // 啟動(dòng)AMS
    traceBeginAndSlog("StartActivityManager");
    mActivityManagerService = mSystemServiceManager.startService(
            ActivityManagerService.Lifecycle.class).getService();
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);
    traceEnd();
    ...
}

private void startOtherServices() {
    ...
    // 告訴AMS可以執(zhí)行第三方代碼,并完成systemserver的初始化涂臣。
    // 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.
    mActivityManagerService.systemReady(() -> {...}, BOOT_TIMINGS_TRACE_LOG);
}

2盾计、systemReady

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
    ...
    synchronized (this) {
        ...
        // Start up initial activity.
        mBooting = true;
        ...
        // 啟動(dòng)初始Activity
        startHomeActivityLocked(currentUserId, "systemReady");
        ...
    }
}

在AMS的systemReady方法中,通過(guò)調(diào)用startHomeActivityLocked來(lái)啟動(dòng)初始Activity赁遗。

3署辉、startHomeActivityLocked

public static final String ACTION_MAIN = "android.intent.action.MAIN";
public static final String CATEGORY_HOME = "android.intent.category.HOME";
String mTopAction = Intent.ACTION_MAIN;

// 獲取home的intent
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;
}

// 啟動(dòng)homeActivity
boolean startHomeActivityLocked(int userId, String reason) {
    ...
    // 獲取首頁(yè)Intent
    Intent intent = getHomeIntent();
    // 獲取activity的信息
    ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
    if (aInfo != null) {
        intent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
        // Don't do this if the home app is currently being
        // instrumented.
        aInfo = new ActivityInfo(aInfo);
        aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
        ProcessRecord app = getProcessRecordLocked(aInfo.processName,
                aInfo.applicationInfo.uid, true);
        if (app == null || app.instr == null) {
            intent.setFlags(intent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
            final int resolvedUserId = UserHandle.getUserId(aInfo.applicationInfo.uid);
            // For ANR debugging to verify if the user activity is the one that actually
            // launched.
            final String myReason = reason + ":" + userId + ":" + resolvedUserId;
            
            // 啟動(dòng)Home activity
            mActivityStartController.startHomeActivity(intent, aInfo, myReason);
        }
    } else {...}
    return true;
}

首先, 通過(guò)getHomeIntent獲取到Intent岩四;
然后哭尝, 通過(guò)resolveActivityInfo得到Activity;
最后剖煌, 通過(guò)mActivityStartController.startHomeActivity啟動(dòng)Activity材鹦。

下面對(duì)resolveActivityInfomActivityStartController.startHomeActivity 進(jìn)行分析。

4耕姊、resolveActivityInfo

private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
    ActivityInfo ai = null;
    // 由于mTopComponent是null桶唐,在getHomeIntent設(shè)置的就是null,所以這里得到的intent也是null茉兰。
    ComponentName comp = intent.getComponent();
    try {
        if (comp != null) {
           ...
        } else {
            ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
                    intent,
                    intent.resolveTypeIfNeeded(mContext.getContentResolver()),
                    flags, userId);
            if (info != null) {
                ai = info.activityInfo;
            }
        }
    } catch (RemoteException e) {...}
    return ai;
}

// AppGlobals的getPackageManager尤泽,調(diào)用ActivityThread的方法
public static IPackageManager getPackageManager() {
    return ActivityThread.getPackageManager();
}

// 通過(guò)binder獲取到PMS的代理對(duì)象
public static IPackageManager getPackageManager() {
    if (sPackageManager != null) {
        return sPackageManager;
    }
    IBinder b = ServiceManager.getService("package");
    sPackageManager = IPackageManager.Stub.asInterface(b);
    return sPackageManager;
}

由于mTopComponent是null,在getHomeIntent設(shè)置的就是null邦邦,所以這里得到的intent也是null安吁;因此通過(guò)PMS的resolveIntent獲取數(shù)據(jù)。

5燃辖、resolveIntent

public ResolveInfo resolveIntent(Intent intent, String resolvedType,
        int flags, int userId) {
    return resolveIntentInternal(intent, resolvedType, flags, userId, false,
            Binder.getCallingUid());
}

private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
        int flags, int userId, boolean resolveForStart, int filterCallingUid) {
    try {
        ...
        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
                flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
        // 選擇合適的activity鬼店,某些場(chǎng)景(如:url)可能多個(gè)app支持打開(kāi),需要讓用戶(hù)選擇
        final ResolveInfo bestChoice =
                chooseBestActivity(intent, resolvedType, flags, query, userId);
        return bestChoice;
    } finally {...}
}

resolveIntent調(diào)用到resolveIntentInternal黔龟,其中通過(guò)queryIntentActivitiesInternal查找Activity妇智,通過(guò)chooseBestActivity選擇合適的Activity進(jìn)行返回滥玷。

6、queryIntentActivitiesInternal

private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
        String resolvedType, int flags, int filterCallingUid, int userId,
        boolean resolveForStart, boolean allowDynamicSplits) {
    // 由上下文可知巍棱,這里為null
    final String pkgName = intent.getPackage();
    ComponentName comp = intent.getComponent();
    if (comp == null) {
        if (intent.getSelector() != null) {
            intent = intent.getSelector();
            comp = intent.getComponent();
        }
    }
    // 情況一:由于comp==null惑畴,不走這里
    if (comp != null) {
        final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
        final ActivityInfo ai = getActivityInfo(comp, flags, userId);
        ...
        return applyPostResolutionFilter(
                list, instantAppPkgName, allowDynamicSplits, filterCallingUid, resolveForStart,
                userId, intent);
    }
    // reader
    List<ResolveInfo> result;
    synchronized (mPackages) {
        if (pkgName == null) {
            // 情況二:通過(guò)userid查詢(xún)intent
            List<CrossProfileIntentFilter> matchingFilters = getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
            // Check for results that need to skip the current profile.
            ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
                    resolvedType, flags, userId);
            if (xpResolveInfo != null) {
                List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
                xpResult.add(xpResolveInfo);
                return applyPostResolutionFilter(
                        filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
                        allowDynamicSplits, filterCallingUid, resolveForStart, userId, intent);
            }
            // Check for results in the current profile.
            result = filterIfNotSystemUser(mActivities.queryIntent(
                    intent, resolvedType, flags, userId), userId);
            ...
            boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
            xpResolveInfo = queryCrossProfileIntents(
                    matchingFilters, intent, resolvedType, flags, userId,
                    hasNonNegativePriorityResult);
            ...
        } else {
            // 情況三:從pkg中查找
            final PackageParser.Package pkg = mPackages.get(pkgName);
            result = null;
            if (pkg != null) {
                result = filterIfNotSystemUser(
                        mActivities.queryIntentForPackage(
                                intent, resolvedType, flags, pkg.activities, userId),
                        userId);
            }
            ...
        }
    }
    ...
    return applyPostResolutionFilter(
            result, instantAppPkgName, allowDynamicSplits, filterCallingUid, resolveForStart,
            userId, intent);
}

該方法分三種情況:
1、comp != null:通過(guò)getActivityInfo -> getActivityInfoInternal 查找Activity的信息航徙;
2如贷、comp == null && pkgName == null:通過(guò)userid查詢(xún)intent;
3到踏、comp == null && pkgName != null:通過(guò)pkg的信息查找intent杠袱。

由前文分析可知,此處走分支2窝稿,調(diào)用querySkipCurrentProfileIntents楣富。

7、querySkipCurrentProfileIntents

private ResolveInfo querySkipCurrentProfileIntents(
        List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
        int flags, int sourceUserId) {
    if (matchingFilters != null) {
        int size = matchingFilters.size();
        for (int i = 0; i < size; i ++) {
            CrossProfileIntentFilter filter = matchingFilters.get(i);
            if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
                // Checking if there are activities in the target user that can handle the
                // intent.
                ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
                        resolvedType, flags, sourceUserId);
                if (resolveInfo != null) {
                    return resolveInfo;
                }
            }
        }
    }
    return null;
}

private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
        String resolvedType, int flags, int sourceUserId) {
    int targetUserId = filter.getTargetUserId();
    List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
            resolvedType, flags, targetUserId);
    if (resultTargetUser != null && isUserEnabled(targetUserId)) {
        // If all the matches in the target profile are suspended, return null.
        for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
            if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
                    & ApplicationInfo.FLAG_SUSPENDED) == 0) {
                return createForwardingResolveInfoUnchecked(filter, sourceUserId,
                        targetUserId);
            }
        }
    }
    return null;
}

querySkipCurrentProfileIntents最終會(huì)調(diào)用到createForwardingResolveInfo方法伴榔,可以看到方法內(nèi)部通過(guò)mActivities.queryIntent() 查找Activity的信息纹蝴。其他方法也是類(lèi)似的邏輯,不再敘述踪少,此處找到的Activity是com.android.launcher3.Launcher 塘安。

二、AMS啟動(dòng)Activity的處理工作

1秉馏、mActivityStartController.startHomeActivity

首先看看mActivityStartController是什么:

// AMS的構(gòu)造函數(shù)中直接new
public ActivityManagerService(Context systemContext) {
    ...
    mActivityStartController = new ActivityStartController(this);
    ...
}

// 在ActivityStartController構(gòu)造函數(shù)中耙旦,new了DefaultFactory。
ActivityStartController(ActivityManagerService service) {
    this(service, service.mStackSupervisor,
            new DefaultFactory(service, service.mStackSupervisor,
                new ActivityStartInterceptor(service, service.mStackSupervisor)));
}

@VisibleForTesting
ActivityStartController(ActivityManagerService service, ActivityStackSupervisor supervisor,
        Factory factory) {
    mService = service;
    mSupervisor = supervisor;
    mHandler = new StartHandler(mService.mHandlerThread.getLooper());
    mFactory = factory;
    mFactory.setController(this);
    mPendingRemoteAnimationRegistry = new PendingRemoteAnimationRegistry(service,
            service.mHandler);
}

可以看到萝究,mActivityStartController就是一個(gè)ActivityStartController實(shí)例免都,它的屬性mFactory是一個(gè)ActivityStarter.DefaultFactory的對(duì)象。

void startHomeActivity(Intent intent, ActivityInfo aInfo, String reason) {
    mSupervisor.moveHomeStackTaskToTop(reason);
    // 啟動(dòng)Activity
    mLastHomeActivityStartResult = obtainStarter(intent, "startHomeActivity: " + reason)
            .setOutActivity(tmpOutRecord)
            .setCallingUid(0)
            .setActivityInfo(aInfo)
            .execute();
    mLastHomeActivityStartRecord = tmpOutRecord[0];
    if (mSupervisor.inResumeTopActivity) {
        // If we are in resume section already, home activity will be initialized, but not
        // resumed (to avoid recursive resume) and will stay that way until something pokes it
        // again. We need to schedule another resume.
        mSupervisor.scheduleResumeTopActivities();
    }
}

在startHomeActivity中帆竹,通過(guò)obtainStarter().execute()啟動(dòng)Activity绕娘。

2、obtainStarter()

// 這里執(zhí)行的ActivityStarter.DefaultFactory的obtain栽连。
ActivityStarter obtainStarter(Intent intent, String reason) {
    return mFactory.obtain().setIntent(intent).setReason(reason);
}

// ontain直接生成了ActivityStarter對(duì)象
public ActivityStarter obtain() {
    ActivityStarter starter = mStarterPool.acquire();
    if (starter == null) {
        starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
    }
    return starter;
}

通過(guò)obtainStarter調(diào)用了ActivityStarter.DefaultFactory的obtain险领,直接返回了一個(gè)新的ActivityStarter。

3秒紧、ActivityStarter.execute()

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.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);
        } 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);
        }
    } finally {
        onExecutionComplete();
    }
}

這里由于沒(méi)有設(shè)置mayWait绢陌,所以會(huì)走下方的邏輯。

4熔恢、startActivity

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
        String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
        String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
        SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
        ActivityRecord[] outActivity, TaskRecord inTask, String reason,
        boolean allowPendingRemoteAnimationRegistryLookup) {
    ...
    mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
            aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
            callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
            options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
            inTask, allowPendingRemoteAnimationRegistryLookup);
    ...
    return getExternalResult(mLastStartActivityResult);
}

private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
                          String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
                          IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                          IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
                          String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
                          SafeActivityOptions options,
                          boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
                          TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup) {
    ...
    // 生成ActivityRecord
    ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
            callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
            resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
    ...
    // 繼續(xù)調(diào)用重載方法
    return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
            true /* doResume */, checkedOptions, inTask, outActivity);
}

private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
                          IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                          int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                          ActivityRecord[] outActivity) {
    int result = START_CANCELED;
    try {
        mService.mWindowManager.deferSurfaceLayout();
        result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                startFlags, doResume, options, inTask, outActivity);
    } finally {
        ...
    }
    postStartActivityProcessing(r, result, mTargetStack);
    return result;
}

startActivity會(huì)調(diào)用多個(gè)重載方法脐湾,期間生成ActivityRecord,并調(diào)用startActivityUnchecked繼續(xù)進(jìn)行操作叙淌。

5秤掌、startActivityUnchecked

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
                                   IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                                   int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
                                   ActivityRecord[] outActivity) {
    // 處理啟動(dòng)模式
    computeLaunchingTaskFlags();

    ...處理?xiàng)O嚓P(guān)的邏輯...

    mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
            mOptions);
    if (mDoResume) {
        final ActivityRecord topTaskActivity = mStartActivity.getTask().topRunningActivityLocked();
        if (!mTargetStack.isFocusable()
                || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                && mStartActivity != topTaskActivity)) {
            ...
        } else {
            // If the target stack was not previously focusable (previous top running activity
            // on that stack was not visible) then any prior calls to move the stack to the
            // will not update the focused stack.  If starting the new activity now allows the
            // task stack to be focusable, then ensure that we now update the focused stack
            // accordingly.
            if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
                mTargetStack.moveToFront("startActivityUnchecked");
            }
            mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                    mOptions);
        }
    } else if (mStartActivity != null) {
        mSupervisor.mRecentTasks.add(mStartActivity.getTask());
    }
    ...
    return START_SUCCESS;
}

該方法處理啟動(dòng)模式愁铺、棧相關(guān)的邏輯,并通過(guò)resumeFocusedStackTopActivityLocked繼續(xù)執(zhí)行闻鉴。

6茵乱、resumeFocusedStackTopActivityLocked

boolean resumeFocusedStackTopActivityLocked(
        ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
    if (!readyToResume()) {
        return false;
    }
    if (targetStack != null && isFocusedStack(targetStack)) {
        return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
    }
    final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
    if (r == null || !r.isState(RESUMED)) {
        mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
    } else if (r.isState(RESUMED)) {
        // Kick off any lingering app transitions form the MoveTaskToFront operation.
        mFocusedStack.executeAppTransition(targetOptions);
    }
    return false;
}

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
    ...
    try {
        ...
        result = resumeTopActivityInnerLocked(prev, options);
        ...
    } finally {... }
    return result;
}

通過(guò)調(diào)用鏈 resumeFocusedStackTopActivityLocked -> resumeTopActivityUncheckedLocked -> resumeTopActivityInnerLocked 最終調(diào)用resumeTopActivityInnerLocked方法。

7孟岛、resumeTopActivityInnerLocked

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    ...
    
    // 這里找到的就是Launcher
    final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
    ...
    
    // mResumedActivity == null瓶竭,不走startPausingLocked
    if (mResumedActivity != null) {
        pausing |= startPausingLocked(userLeaving, false, next, false);
    }
    ...
    
    if (next.app != null && next.app.thread != null) {
        ...
    } else {
        ...
        // 啟動(dòng)Activity
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
    }
    if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
    return true;
}

在resumeTopActivityInnerLocked中,通過(guò)一系列調(diào)用蚀苛,會(huì)調(diào)用到startSpecificActivityLocked方法在验。

8、startSpecificActivityLocked

void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
    // Is this activity's application already running?
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
            r.info.applicationInfo.uid, true);
    getLaunchTimeTracker().setLaunchTime(r);
    if (app != null && app.thread != null) {
       ...
    }
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
            "activity", r.intent.getComponent(), false, false, true);
}

通過(guò)AMS的startProcessLocked啟動(dòng)App進(jìn)程堵未。

三、App進(jìn)程啟動(dòng)

1盏触、startProcessLocked

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, isolated, 0 /* isolatedUid */, keepIfLarge,
            null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */,
            null /* crashHandler */);
}


final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
                                       boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
                                       boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
                                       String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
    long startTime = SystemClock.elapsedRealtime();
    ProcessRecord app;
    ...
    if (app == null) {
        ...
        // 生成新的ProcessRecord
        app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
        ...
    } else {...}
    ...
    
    final boolean success = startProcessLocked(app, hostingType, hostingNameStr, abiOverride);
    checkTime(startTime, "startProcess: done starting proc!");
    return success ? app : null;
}

startProcessLocked會(huì)調(diào)用重載方法渗蟹,然后通過(guò)newProcessRecordLocked生成新的ProcessRecord,之后會(huì)調(diào)用startProcessLocked進(jìn)一步處理赞辩。

2雌芽、startProcessLocked

private final boolean startProcessLocked(ProcessRecord app,
        String hostingType, String hostingNameStr, String abiOverride) {
    return startProcessLocked(app, hostingType, hostingNameStr,
            false /* disableHiddenApiChecks */, abiOverride);
}


private final boolean startProcessLocked(ProcessRecord app, String hostingType,
                                         String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {
    ...
    try {
        ...
        final String entryPoint = "android.app.ActivityThread";
        
        return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids,
                runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
                startTime);
    } catch (RuntimeException e) {...}
}


private boolean startProcessLocked(String hostingType, String hostingNameStr, String entryPoint,
                                   ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
                                   String seInfo, String requiredAbi, String instructionSet, String invokeWith,
                                   long startTime) {
    ...
    // 同步還是異步
    if (mConstants.FLAG_PROCESS_START_ASYNC) {
        mProcStartHandler.post(() -> {
            try {
                ...
                final ProcessStartResult startResult = startProcess(app.hostingType, entryPoint,
                        app, app.startUid, gids, runtimeFlags, mountExternal, app.seInfo,
                        requiredAbi, instructionSet, invokeWith, app.startTime);
                synchronized (ActivityManagerService.this) {
                    handleProcessStartedLocked(app, startResult, startSeq);
                }
            } catch (RuntimeException e) {...}
        });
        return true;
    } else {
        try {
            final ProcessStartResult startResult = startProcess(hostingType, entryPoint, app,
                    uid, gids, runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet,
                    invokeWith, startTime);
            handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper,
                    startSeq, false);
        } catch (RuntimeException e) {...}
        return app.pid > 0;
    }
}

startProcessLocked通過(guò)一系列重載方法,最終調(diào)用startProcess進(jìn)行處理辨嗽,注意這里的entryPoint = "android.app.ActivityThread"

3世落、startProcess

private ProcessStartResult startProcess(String hostingType, String entryPoint,
                                        ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
                                        String seInfo, String requiredAbi, String instructionSet, String invokeWith,
                                        long startTime) {
    try {
        ...
        final ProcessStartResult startResult;
        if (hostingType.equals("webview_service")) {...} else {
            startResult = Process.start(entryPoint,
                    app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                    app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                    app.info.dataDir, invokeWith,
                    new String[] {PROC_START_SEQ_IDENT + app.startSeq});
        }
        checkTime(startTime, "startProcess: returned from zygote!");
        return startResult;
    } finally {...}
}

通過(guò)Process.start()啟動(dòng)進(jìn)程

4、通過(guò)socket通知zygote進(jìn)程

通過(guò)如下掉用鏈糟需,會(huì)將啟動(dòng)進(jìn)程的數(shù)據(jù)發(fā)送給zygote進(jìn)程屉佳,
ProcessStartResult.start() ->
ZygoteProcess.start() ->
ZygoteProcess.startViaZygote() ->
ZygoteProcess.zygoteSendArgsAndGetResult() ->
ZygoteProcess.attemptZygoteSendArgsAndGetResult() ->
{ zygoteWriter.write(msgStr); zygoteWriter.flush(); }

Zygote進(jìn)程簡(jiǎn)介可知,zygote進(jìn)程啟動(dòng)后洲押,會(huì)啟動(dòng)輪詢(xún)等待消息武花。

在zygote中,會(huì)通過(guò)ZygoteConnection.processOneCommand()處理client發(fā)送來(lái)的消息杈帐,然后通過(guò)Zygote.forkAndSpecialize() fork出進(jìn)程体箕,在通過(guò)ZygoteConnection.handleChildProc() -> ZygoteInit.zygoteInit() -> RuntimeInit.commonInit() -> RuntimeInit.applicationInit() -> RuntimeInit.findStaticMain()調(diào)用main方法。由上文可知挑童,這里會(huì)調(diào)用到android.app.ActivityThread的main方法累铅。

四、Activity生命周期

1站叼、ActivityThread

final ApplicationThread mAppThread = new ApplicationThread();

public static void main(String[] args) {
    ...
    Looper.prepareMainLooper();
    ...
    // 創(chuàng)建ActivityThread
    ActivityThread thread = new ActivityThread();
    // 執(zhí)行attach
    thread.attach(false, startSeq);
    ...
    // 啟動(dòng)looper
    Looper.loop();
}

private void attach(boolean system, long startSeq) {
    ...
    if (!system) {
        ...
        // 獲取AMS代理
        final IActivityManager mgr = ActivityManager.getService();
        try {
            mgr.attachApplication(mAppThread, startSeq);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
        ...
    } else {...}
}

ActivityThread的main方法中娃兽,通過(guò)構(gòu)造方法生成了ActivityThread,同時(shí)生成了ApplicationThread大年;然后通過(guò)attach方法换薄,與AMS進(jìn)行通信玉雾;最后啟動(dòng)looper等待處理消息。

2轻要、attachApplication

 public final void attachApplication(IApplicationThread thread, long startSeq) {
     synchronized (this) {
         ...
         attachApplicationLocked(thread, callingPid, callingUid, startSeq);
         ...
     }
 }

private final boolean attachApplicationLocked(IApplicationThread thread,
                                              int pid, int callingUid, long startSeq) {
    ...
    // 回調(diào)App綁定方法
    thread.bindApplication(processName, appInfo, providers,
            app.instr.mClass,
            profilerInfo, app.instr.mArguments,
            app.instr.mWatcher,
            app.instr.mUiAutomationConnection, testMode,
            mBinderTransactionTrackingEnabled, enableTrackAllocation,
            isRestrictedBackupMode || !normalMode, app.persistent,
            new Configuration(getGlobalConfiguration()), app.compat,
            getCommonServicesLocked(app.isolated),
            mCoreSettingsObserver.getCoreSettingsLocked(),
            buildSerial, isAutofillCompatEnabled);
    ...
    // See if the top visible activity is waiting to run in this process...
    if (normalMode) {
        try {
            if (mStackSupervisor.attachApplicationLocked(app)) {
                didSomething = true;
            }
        } catch (Exception e) {...}
    }
    ...
    return true;
}

attachApplication會(huì)調(diào)用attachApplicationLocked复旬;然后通過(guò)bindApplication回調(diào)到App進(jìn)程,發(fā)送BIND_APPLICATION消息冲泥,通過(guò)handleBindApplication做一些綁定后的操作:創(chuàng)建mInstrumentation驹碍,并回調(diào)Application的onCreate();最后通過(guò)mStackSupervisor.attachApplicationLocked(app)進(jìn)一步處理凡恍。

3志秃、attachApplicationLocked

boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
    final String processName = app.processName;
    boolean didSomething = false;
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
        for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
            final ActivityStack stack = display.getChildAt(stackNdx);
            if (!isFocusedStack(stack)) {
                continue;
            }
            stack.getAllRunningVisibleActivitiesLocked(mTmpActivityList);
            final ActivityRecord top = stack.topRunningActivityLocked();
            final int size = mTmpActivityList.size();
            for (int i = 0; i < size; i++) {
                final ActivityRecord activity = mTmpActivityList.get(i);
                if (activity.app == null && app.uid == activity.info.applicationInfo.uid
                        && processName.equals(activity.processName)) {
                    try {
                        if (realStartActivityLocked(activity, app,
                                top == activity /* andResume */, true /* checkConfig */)) {
                            didSomething = true;
                        }
                    } catch (RemoteException e) {
                        Slog.w(TAG, "Exception in new application when starting activity "
                                + top.intent.getComponent().flattenToShortString(), e);
                        throw e;
                    }
                }
            }
        }
    }
    if (!didSomething) {
        ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
    }
    return didSomething;
}

attachApplicationLocked調(diào)用realStartActivityLocked

4、realStartActivityLocked

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
                                      boolean andResume, boolean checkConfig) throws RemoteException {
    ...
    try {
        ...
        try {
            ...
            // 添加啟動(dòng)事務(wù)
            clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
                    System.identityHashCode(r), r.info,
                    // TODO: Have this take the merged configuration instead of separate global
                    // and override configs.
                    mergedConfiguration.getGlobalConfiguration(),
                    mergedConfiguration.getOverrideConfiguration(), r.compat,
                    r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
                    r.persistentState, results, newIntents, mService.isNextTransitionForward(),
                    profilerInfo));
            // 添加resume或pause事務(wù)
            final ActivityLifecycleItem lifecycleItem;
            if (andResume) {
                lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
            } else {
                lifecycleItem = PauseActivityItem.obtain();
            }
            clientTransaction.setLifecycleStateRequest(lifecycleItem);
            // 執(zhí)行事務(wù)
            mService.getLifecycleManager().scheduleTransaction(clientTransaction);
            ...
        } catch (RemoteException e) {...}
    } finally {...}
    ...
    return true;
}

添加啟動(dòng)Activity和OnResume的事務(wù)嚼酝,并通過(guò)AMS的LifecycleManager執(zhí)行事務(wù)浮还。

5、scheduleTransaction

void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    final IApplicationThread client = transaction.getClient();
    transaction.schedule();
    ...
}

public void schedule() throws RemoteException {
    mClient.scheduleTransaction(this);
}

public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
    ActivityThread.this.scheduleTransaction(transaction);
}

void scheduleTransaction(ClientTransaction transaction) {
    transaction.preExecute(this);
    sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

LifecycleManager是ClientLifecycleManager類(lèi)型闽巩;
transaction是ClientTransaction類(lèi)型钧舌;
mClient是IApplicaItionThread類(lèi)型;
ActivityThread繼承自ClientTransactionHandler涎跨。

LifecycleManager.scheduleTransaction()調(diào)用ClientTransaction.schedule()洼冻,然后調(diào)用mClient.scheduleTransaction(this);mClient會(huì)通過(guò)Binder將數(shù)據(jù)發(fā)送到App進(jìn)程隅很,調(diào)用ApplicationThread.scheduleTransaction()撞牢,然后調(diào)用到ActivityThread.scheduleTransaction();由于ActivityThread繼承自ClientTransactionHandler叔营,最終會(huì)調(diào)用到ClientTransactionHandler.scheduleTransaction()屋彪;在這里,發(fā)送了類(lèi)型為EXECUTE_TRANSACTION的消息审编。

6撼班、EXECUTE_TRANSACTION消息處理

public void handleMessage(Message msg) {
    if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
    switch (msg.what) {
        case EXECUTE_TRANSACTION:
            final ClientTransaction transaction = (ClientTransaction) msg.obj;
            mTransactionExecutor.execute(transaction);
            ...
    }
}

public void execute(ClientTransaction transaction) {
    final IBinder token = transaction.getActivityToken();
    // 先執(zhí)行callBack
    executeCallbacks(transaction);
    // 再執(zhí)行LifeCycle
    executeLifecycleState(transaction);
    ...
}

在case分之中,通過(guò)TransactionExecutor.execute()對(duì)事物進(jìn)行處理垒酬,在execute中砰嘁,先執(zhí)行callBack,再執(zhí)行LifeCycle勘究。

7矮湘、LaunchActivityItem.execute()

由上文我們知道,callBack是LaunchActivityItem口糕,lifeCycle是ResumeActivityItem缅阳。

public void executeCallbacks(ClientTransaction transaction) {
    final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
    ...
    final int size = callbacks.size();
    for (int i = 0; i < size; ++i) {
        final ClientTransactionItem item = callbacks.get(i);
        ...
        
        item.execute(mTransactionHandler, token, mPendingActions);
        ...
    }
}

public void execute(ClientTransactionHandler client, IBinder token,
        PendingTransactionActions pendingActions) {
    Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
    ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
            mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
            mPendingResults, mPendingNewIntents, mIsForward,
            mProfilerInfo, client);
    client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
    Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}

LaunchActivityItem的execute會(huì)調(diào)用client.handleLaunchActivity進(jìn)行處理,由上文我們知道ActivityThread繼承自ClientTransactionHandler,因此調(diào)用到ActivityThread內(nèi)部十办。

8秀撇、handleLaunchActivity

public Activity handleLaunchActivity(ActivityThread.ActivityClientRecord r,
                                     PendingTransactionActions pendingActions, Intent customIntent) {
    ...
    final Activity a = performLaunchActivity(r, customIntent);
    ...
    return a;
}

private Activity performLaunchActivity(ActivityThread.ActivityClientRecord r, Intent customIntent) {
    ActivityInfo aInfo = r.activityInfo;
    ...
    ComponentName component = r.intent.getComponent();
    ...
    
    // 創(chuàng)建Activity的Context
    ContextImpl appContext = createBaseContextForActivity(r);
    Activity activity = null;
    try {
        // 實(shí)例化Activity
        ClassLoader cl = appContext.getClassLoader();
        activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
        ...
    } catch (Exception e) {...}
    try {
        ...
        if (activity != null) {
            ...
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            ...
        }
        ...
    } catch (SuperNotCalledException e) {
        ...
    } catch (Exception e) {...}
    return activity;
}

public void callActivityOnCreate(Activity activity, Bundle icicle) {
    prePerformCreate(activity);
    activity.performCreate(icicle);
    postPerformCreate(activity);
}

final void performCreate(Bundle icicle) {
    performCreate(icicle, null);
}

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
    ...
    if (persistentState != null) {
        onCreate(icicle, persistentState);
    } else {
        onCreate(icicle);
    }
    ...
}

通過(guò)performLaunchActivity處理Activity的啟動(dòng),包括創(chuàng)建Context向族,實(shí)例化Activity呵燕,并通過(guò)mInstrumentation.callActivityOnCreate -> Activity.performCreate -> Activity.onCreate調(diào)用到onCreate方法。

9件相、executeLifecycleState

private void executeLifecycleState(ClientTransaction transaction) {
    // 取到的是ResumeActivityItem
    final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
    ...
    final IBinder token = transaction.getActivityToken();
    final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
    ...
    // Cycle to the state right before the final requested state.
    cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
    // Execute the final transition with proper parameters.
    lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
    lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}


private void cycleToPath(ActivityClientRecord r, int finish,
                         boolean excludeLastState) {
    // start 是 ON_CREATE再扭,finish 是 ON_RESUME
    final int start = r.getLifecycleState();
    log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
    final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
    performLifecycleSequence(r, path);
}


public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
    ...
    // 將中間缺少的生命周期補(bǔ)全
    mLifecycleSequence.clear();
    if (finish >= start) {
        // just go there
        for (int i = start + 1; i <= finish; i++) {
            mLifecycleSequence.add(i);
        }
    } else { // finish < start, can't just cycle down
        ...
    }
    // 移除最后一個(gè)狀態(tài),需要額外處理
    if (excludeLastState && mLifecycleSequence.size() != 0) {
        mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
    }
    return mLifecycleSequence;
}

private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
        final int size = path.size();
        for (int i = 0, state; i < size; i++) {
            state = path.get(i);
            log("Transitioning to state: " + state);
            switch (state) {
                case ON_CREATE:
                    mTransactionHandler.handleLaunchActivity(r, mPendingActions,
                            null /* customIntent */);
                    break;
                case ON_START:
                    mTransactionHandler.handleStartActivity(r, mPendingActions);
                    break;
                case ON_RESUME:
                    mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
                            r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
                    break;
                case ON_PAUSE:
                    mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
                            false /* userLeaving */, 0 /* configChanges */, mPendingActions,
                            "LIFECYCLER_PAUSE_ACTIVITY");
                    break;
                case ON_STOP:
                    mTransactionHandler.handleStopActivity(r.token, false /* show */,
                            0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
                            "LIFECYCLER_STOP_ACTIVITY");
                    break;
                case ON_DESTROY:
                    mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
                            0 /* configChanges */, false /* getNonConfigInstance */,
                            "performLifecycleSequence. cycling to:" + path.get(size - 1));
                    break;
                case ON_RESTART:
                    mTransactionHandler.performRestartActivity(r.token, false /* start */);
                    break;
                default:
                    throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
            }
        }
    }

執(zhí)行完畢executeCallbacks后夜矗,會(huì)執(zhí)行到executeLifecycleState泛范,該方法會(huì)取到ResumeActivityItem,之后通過(guò)cycleToPath補(bǔ)全中間的狀態(tài)紊撕,然后執(zhí)行ResumeActivityItem的execute方法罢荡。

由于start 是 ON_CREATE,finish 是 ON_RESUME对扶,所以補(bǔ)齊ON_START狀態(tài)柠傍,然后通過(guò)performLifecycleSequence繼續(xù)執(zhí)行,在ON_START分支中辩稽,通過(guò)mTransactionHandler.handleStartActivity()執(zhí)行onStart方法,我們知道此處的mTransactionHandler就是ActivityThread从媚,之后通過(guò)activity.performStart -> mInstrumentation.callActivityOnStart -> activity.onStart 調(diào)用到onStart方法逞泄。

最后通過(guò)ResumeActivityItem.execute -> ActivityThread.handleResumeActivity -> ActivityThread.performResumeActivity -> activity.performResume -> mInstrumentation.callActivityOnResume -> activity.onResume;調(diào)用到onResume方法拜效。

點(diǎn)擊屏幕圖標(biāo)啟動(dòng)Activity

frameworks/base/core/java/android/app/Activity.java
frameworks/base/core/java/android/app/Instrumentation.java

1喷众、startActivity

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

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

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 {...}
}

startActivity會(huì)通過(guò)重載方法調(diào)用到startActivityForResult,然后通過(guò)mInstrumentation.execStartActivity進(jìn)行啟動(dòng)紧憾。

2到千、Instrumentation.execStartActivity

public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, android.app.Activity target,
        Intent intent, int requestCode, Bundle options) {
    ...
    try {
        ...
        int result = ActivityManager.getService()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()),
                    token, target != null ? target.mEmbeddedID : null,
                    requestCode, 0, null, options);
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {...}
    return null;
}

通過(guò)binder調(diào)用AMS的startActivity。

3赴穗、AMS.startActivity

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

public final 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*/);
}

public final 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("startActivity");
    userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
            Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
    // TODO: Switch to user app stacks here.
    return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
            .setCaller(caller)
            .setCallingPackage(callingPackage)
            .setResolvedType(resolvedType)
            .setResultTo(resultTo)
            .setResultWho(resultWho)
            .setRequestCode(requestCode)
            .setStartFlags(startFlags)
            .setProfilerInfo(profilerInfo)
            .setActivityOptions(bOptions)
            .setMayWait(userId)
            .execute();
}

startActivity通過(guò)startActivityAsUser的重載方法憔四,調(diào)用到mActivityStartController.obtainStarter().execute()。

4般眉、mActivityStartController.obtainStarter().execute()

ActivityStarter obtainStarter(Intent intent, String reason) {
    return mFactory.obtain().setIntent(intent).setReason(reason);
}

int execute() {
    try {
        if (mRequest.mayWait) {
            return startActivityMayWait(mRequest.caller, mRequest.callingUid,
                    mRequest.callingPackage, 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);
        } else {
            ...
        }
    } finally {...}
}

mActivityStartController.obtainStarter()會(huì)得到ActivityStarter對(duì)象了赵,然后執(zhí)行execute方法,調(diào)用startActivityMayWait甸赃。

5柿汛、startActivityMayWait

private int startActivityMayWait(IApplicationThread caller, int callingUid,
        String callingPackage, Intent intent, String resolvedType,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        IBinder resultTo, String resultWho, int requestCode, int startFlags,
        ProfilerInfo profilerInfo, WaitResult outResult,
        Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
        int userId, TaskRecord inTask, String reason,
        boolean allowPendingRemoteAnimationRegistryLookup) {
    ...
    ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
            0 /* matchFlags */,
                    computeResolveFilterUid(
                            callingUid, realCallingUid, mRequest.filterCallingUid));
    ...
    ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
    synchronized (mService) {
        ...
        int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
                voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
                callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
                ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
                allowPendingRemoteAnimationRegistryLookup);
        ...
        return res;
    }
}

startActivityMayWait中通過(guò)resolveIntent獲取到ResolveInfo;然后通過(guò)startActivity進(jìn)行操作埠对。

6络断、resolveIntent

ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags,
        int filterCallingUid) {
    synchronized (mService) {
        try {
            ...
            try {
                return mService.getPackageManagerInternalLocked().resolveIntent(
                        intent, resolvedType, modifiedFlags, userId, true, filterCallingUid);
            } finally {...}
        } finally {...}
    }
}

在resolveIntent中裁替,通過(guò)PMS進(jìn)行數(shù)據(jù)解析。

7貌笨、getPackageManagerInternalLocked

PackageManagerInternal getPackageManagerInternalLocked() {
    if (mPackageManagerInt == null) {
        mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class);
    }
    return mPackageManagerInt;
}

public class PackageManagerService extends IPackageManager.Stub implements PackageSender {
    ...
    public PackageManagerService(Context context, Installer installer,boolean factoryTest, boolean onlyCore) {
        ...
        // 注冊(cè)本地服務(wù)
        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
        ...
    }

    // 內(nèi)部類(lèi)分瘦,持有PMS
    private class PackageManagerInternalImpl extends PackageManagerInternal {
        ...
        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
                int flags, int userId, boolean resolveForStart, int filterCallingUid) {
            return resolveIntentInternal(
                    intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
        }
        ...
    }
}

在PMS構(gòu)造方法中,注冊(cè)了PackageManagerInternal.class援雇,真正的實(shí)現(xiàn)類(lèi)是PackageManagerInternalImpl枷莉,這樣AMS便可以通過(guò)它與PMS進(jìn)行交互。

8净刮、PMS.getActivityInfoInternal

通過(guò)如下調(diào)用鏈
resolveIntentInternal->queryIntentActivitiesInternal->getActivityInfo->getActivityInfoInternal調(diào)用到getActivityInfoInternal剥哑。

private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
        int filterCallingUid, int userId) {
    ...
    synchronized (mPackages) {
        PackageParser.Activity a = mActivities.mActivities.get(component);
        if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
        if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
            ...
            return PackageParser.generateActivityInfo(
                    a, flags, ps.readUserState(userId), userId);
        }
        if (mResolveComponentName.equals(component)) {
            return PackageParser.generateActivityInfo(
                    mResolveActivity, flags, new PackageUserState(), userId);
        }
    }
    return null;
}

在這里通過(guò)PMS中緩存的Activity信息查找對(duì)應(yīng)的Activity。在找到Activity后淹父,通過(guò)startActivity啟動(dòng)Activity株婴,邏輯與上文內(nèi)容相似,不再贅述暑认。

需要注意的是困介,由于有Launcher程序,因此在執(zhí)行resumeTopActivityInnerLocked時(shí)蘸际,會(huì)通過(guò)startPausingLocked執(zhí)行上一個(gè)頁(yè)面(Launcher)的onPause邏輯座哩。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市粮彤,隨后出現(xiàn)的幾起案子根穷,更是在濱河造成了極大的恐慌,老刑警劉巖导坟,帶你破解...
    沈念sama閱讀 218,122評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件屿良,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡惫周,警方通過(guò)查閱死者的電腦和手機(jī)尘惧,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,070評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)递递,“玉大人喷橙,你說(shuō)我怎么就攤上這事⊙牵” “怎么了重慢?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,491評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀(guān)的道長(zhǎng)逊躁。 經(jīng)常有香客問(wèn)我似踱,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,636評(píng)論 1 293
  • 正文 為了忘掉前任核芽,我火速辦了婚禮囚戚,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘轧简。我一直安慰自己驰坊,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,676評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布哮独。 她就那樣靜靜地躺著拳芙,像睡著了一般。 火紅的嫁衣襯著肌膚如雪皮璧。 梳的紋絲不亂的頭發(fā)上舟扎,一...
    開(kāi)封第一講書(shū)人閱讀 51,541評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音悴务,去河邊找鬼睹限。 笑死,一個(gè)胖子當(dāng)著我的面吹牛讯檐,可吹牛的內(nèi)容都是我干的羡疗。 我是一名探鬼主播,決...
    沈念sama閱讀 40,292評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼别洪,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼叨恨!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起挖垛,我...
    開(kāi)封第一講書(shū)人閱讀 39,211評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤特碳,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后晕换,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,655評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡站宗,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,846評(píng)論 3 336
  • 正文 我和宋清朗相戀三年闸准,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片梢灭。...
    茶點(diǎn)故事閱讀 39,965評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡夷家,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出敏释,到底是詐尸還是另有隱情库快,我是刑警寧澤,帶...
    沈念sama閱讀 35,684評(píng)論 5 347
  • 正文 年R本政府宣布钥顽,位于F島的核電站义屏,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜闽铐,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,295評(píng)論 3 329
  • 文/蒙蒙 一蝶怔、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧兄墅,春花似錦踢星、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,894評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至五督,卻和暖如春藏否,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背概荷。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,012評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工秕岛, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人误证。 一個(gè)月前我還...
    沈念sama閱讀 48,126評(píng)論 3 370
  • 正文 我出身青樓继薛,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親愈捅。 傳聞我的和親對(duì)象是個(gè)殘疾皇子遏考,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,914評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容