AMS剖析(2):Activity在AMS中的启动

前言:前面已经分析了AMS的启动,接下来就开始分析AMS的数据结构以及AMS与ActivityThread的交互;

这一篇我们跟着一个Activity的启动流程,来分析AMS的数据结构,基于android9.0的framework源码;

Activity的启动过程分为两种,一种是根Acitivity的启动过程,另一种是普通Activity的启动过程;

①根Activity指的是应用程序启动的第一个Activity,所以根Activity的启动过程,也称为应用程序的启动过程;

②普通Activity指的是除应用程序启动的第一个Activity之外的其他Activity;

我们分析的是根Activity的启动流程;

接下来慢慢分析:

1.Launcher请求AMS

我们知道,Launcher启动后会将已安装的应用程序的快捷图标显示到桌面,这些应用程序的快捷图标就是启动根Activity的入口;我们就以点击Settings应用即"设置"的快捷图标为例,来分析根Activity的启动流程;

当我们在Launcher中点击Settings图标时会调用如下代码:

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent,optBundle);

点评:将Flag设置为Intent.FLAG_ACTIVITY_NEW_TASK,这样根Activity会在新的任务栈中启动;

Settings的intent中,除了上述的flag信息外,还有如下信息:

Action:android.intent.action.MAIN;
Categories:android.intent.category.LAUNCHER;
Component:要启动的Activity组件,值为com.android.settings/.Settings;
Flag:启动标记,FLAG_ACTIVITY_NEW_TASK;

接下来看startActivity(intent,optBundle)方法在Activity中实现,代码如下:

Activity.java
public void startActivity(Intent intent, @Nullable Bundle options) {
    if (options != null) {
        //第二个参数为-1,表示Launcher不需要知道Activity的启动结果;
        //options为携带的信息,它用于指定启动Activity的自定义动画和缩放动画
        startActivityForResult(intent, -1, options);
    } else {
        startActivityForResult(intent, -1);
    }
}

点评:我们的代码走这一句,startActivityForResult(intent, -1, options),继续看:

public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
        @Nullable Bundle options) {
    if (mParent == null) {
        //mParent表示当前Activity的父类,Launcher没有父亲

        options = transferSpringboardActivityOptions(options);

        //接下来调用Instrumentation的execStartActivity方法
        Instrumentation.ActivityResult ar =
            mInstrumentation.execStartActivity(
                this, mMainThread.getApplicationThread(), mToken, this,
                intent, requestCode, options);
        
        //对于requestCode<0的情况,ar为null;
        //这里的requestCode为-1,表示不需要返回结果
        if (ar != null) {//获取启动Activity的返回结果
            //根据Settings的返回结果,调用Launcher的onActivityResult方法;
            //ar==null,因为mInstrumentation.execStartActivity()的返回结果必定是null;
            //这个属于AMS与AcitivtyThread交互的范畴,先不讨论
            mMainThread.sendActivityResult(
                mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                ar.getResultData());
        }
        if (requestCode >= 0) {
            mStartedActivity = true;
        }
        cancelInputsAndStartExitTransition(options);
    } else {//子Activity,最终调用mInstrumentation.execStartActivity
        if (options != null) {
            mParent.startActivityFromChild(this, intent, requestCode, options);
        } else {
            mParent.startActivityFromChild(this, intent, requestCode);
        }
    }
}

点评:①Instrumentation是用来监控应用程序和系统的交互,启动应用程序的Activity需要与ActivityManagerService交互,因此需要通过Instrumentation代理并监控启动请求的处理;这里的mInstrumentation属于Launcher,我们后面会详细分析根Acitivty的Instrumentation;

②mToken是IBinder类型的对象,其本质是一个BinderProxy,通过该Binder代理可以访问当前Activity(本例为Launcher)在ActivityManagerService中对应的ActivityRecord;ActivityRecord记录了当前Activity的信息, AMS需要获取这些信息;

③mMainThread是ActivityThread类型的对象,表示应用程序主线程,本例中代表的是Launcher的主线程。ActivityThread有一个 ApplicationThread类型的成员变量,定义了调度当前Activity的方法,可以通过mMainThread.getApplicationThread方法返回该成员变量。

这三个变量在后面会详解,这里先简单的介绍一下,知道它们的意义即可;

继续看代码:

Instrumentation.java
public ActivityResult execStartActivity(
        Context who, IBinder contextThread, IBinder token, Activity target,
        Intent intent, int requestCode, Bundle options) {
    IApplicationThread whoThread = (IApplicationThread) contextThread;
    ............
    try {
        intent.migrateExtraStreamToClipData();
        intent.prepareToLeaveProcess(who);
        //调用ActivityManager的getService()方法获取AMS得代理对象,接着调用AMS的startActivity方法
        int result = ActivityManager.getService()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()),
                    token, target != null ? target.mEmbeddedID : null,
                    requestCode, 0, null, options);
        //检查是否启动成功,如果Activity启动失败,result会告诉我们失败的原因
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }

    return null;
}

点评:我们来看ActivityManager.getService()是如何得到AMS的;

ActivityManager.java
public static IActivityManager getService() {
    return IActivityManagerSingleton.get();
}

private static final Singleton<IActivityManager> IActivityManagerSingleton =
        new Singleton<IActivityManager>() {
            @Override
            protected IActivityManager create() {
                //得到IBinder类型的AMS的引用
                final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
                //将"IBinder类型的AMS的引用"转换成"IActivityManager类型的对象",这段代码采用的是AIDL,采用跨进程通信
                final IActivityManager am = IActivityManager.Stub.asInterface(b);
                return am;
            }
        };

点评:从上面得知, mInstrumentation.execStartActivity()最终调用的是AMS.startActivity();

我们先来做个小总结:

①点击Launcher中Settings图标,会调用Launcher.startActivity(),进而调用Launcher的父类Activity的startActivity方法;

②Activity.startActivity()调用Activity.startActivityForResult()方法,传入该方法的requestCode参数为-1,表示Activity启动成功后,不需要执行Launcher.onActivityResult()方法处理返回结果;

③启动Activity需要与系统AMS交互,必须纳入Instrumentation的监控,因此需要将启动请求转交Instrumentation,即调用Instrumentation. execStartActivity方法;

④Instrumentation.execStartActivity()首先通过ActivityMonitor检查启动请求,然后通过ActivityManager.getService()方法获取AMS的代理对象,接着调用AMS的startActivity方法。通过IPC,Binder驱动将处理逻辑从Launcher所在进程切换到AMS所在进程。

接下来我们就进入到AMS了;

 

2.AMS到ApplicaitonThread的调用过程

ActivityManagerService.java
public final int startActivity(IApplicationThread caller, String callingPackage,
        Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
        int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
    //UserHandle.getCallingUserId()表示调用者的UserId,AMS会根据这个UserId来确定调用者的权限
    return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, bOptions,
            UserHandle.getCallingUserId());
}

点评: 在分析AMS的startActivity方法之前,我们先来看一下该方法传递进来的参数信息;

caller:Launcher的ApplicationThread,即请求者的ApplicationThread;

callingPackage:Launcher的包名,即请求者的包名;

intent:意图,这个容易理解;

resolvedType:标识Intent数据的MIME类型,可以通过Intent.setDataAndType()设置,这里可以理解为null;

resultTo:令牌,标识接受返回结果的一方,是一个ActivityRecord的IBinder引用;

resultWho:暂时把它理解成是一个id,与调用者的包名有关;

requestCode:请求码,这里是-1;

startFlags:这里为0;

profilerInfo:这里为null;

bOptions:传递进来的动画参数;

我们发现startActivityAsUser方法比startActivity方法多了一个参数UserHandle.getCallingUserId(),也就是说,startActivityAsUser方法这个方法会获得调用者的UserId,AMS会根据这个UserId来确定调用者的权限;

这些参数都了解了,接下来继续看startActivityAsUser()方法:

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) {
    //多了一个参数true,表示验证调用者
    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) {
    //检查调用者即Launcher进程是否有权限启动Activity,如果没权限,抛出异常
    enforceNotIsolatedCaller("startActivity");

    //检查调用者Laucher这个Activity是否有权限启动Settings,如果没有权限也会抛出异常
    userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
            Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");

    //获取到ActivityStarter,并调用ActivityStarter的execute()方法
    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();
}

点评:上述代码主要是检查调用者的进程以及调用者的权限,最后通过 mActivityStartController.obtainStarter()得到ActivityStarter,ActivityStarter是一个代理类,代理AMS与App进行通信,类似于Activity中的Instrumentation,AMS在每一次startActivity方法的调用过程中,都会创建一个ActivityStarter来进行代理;

得到ActivityStarter后调用ActivityStarter的execute()方法,初始化ActivityStarter的过程是一个典型的Builder模式,继续来看ActivityStarter.execute():

 

ActivityStarter.java
int execute() {
    try {
        if (mRequest.mayWait) {
            //只要调用了setMayWait()方法,mRequest.mayWait就为true,所以走下面这段代码
            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();
    }
}

点评:startActivityMayWait()的返回值就是启动Activity的结果,我们看到startActivityMayWait()方法中有很多参数,mRequest只是一个对象,它用来将AMS中传递过来的参数进行封装,优化了代码;

我们再来看下它多了哪几个参数吧:

mRequest.waitResult:由于不需要等待Activity的返回结果,所以这里为null;

mRequest.globalConfig:全局配置,这里也是null;

mRequest.activityOptions:对bOptions的调整以及封装;

mRequest.ignoreTargetSecurity:是否忽视目标的安全性,这里是false,表示不能忽视;

mRequest.userId:调用者的id;

mRequest.inTask:TaskRecord,启动的Activity,也就是根Activity所在的栈,目前是null;

mRequest.reason:启动Activity的理由,这里的理由就是"startActivityAsUser";

mRequest.allowPendingRemoteAnimationRegistryLookup:允许从Activity开始检查,这里为false,即不允许;

好,下面继续看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) {
    // Refuse possible leaked file descriptors
    if (intent != null && intent.hasFileDescriptors()) {
        throw new IllegalArgumentException("File descriptors passed in Intent");
    }
    mSupervisor.getActivityMetricsLogger().notifyActivityLaunching();

    //传入的intent包含ComponentName的信息,这里的componentSpecified为true
    boolean componentSpecified = intent.getComponent() != null;

    final int realCallingPid = Binder.getCallingPid();
    final int realCallingUid = Binder.getCallingUid();

    //设置callingPid,callingUid,用于区分调用者是否来自于应用程序
    int callingPid;
    if (callingUid >= 0) {
        callingPid = -1;
    } else if (caller == null) {
        //启动Launcher或者使用am start启动一个应用程序时,caller便为null,此时需要记录调用方的PID和UID;
        callingPid = realCallingPid;
        callingUid = realCallingUid;
    } else {
        callingPid = callingUid = -1;
    }

    //后续操作会修改客户端传进来的Inent,这里重新封装,防止修改原始Intent
    final Intent ephemeralIntent = new Intent(intent);
    intent = new Intent(intent);

    //如果是启动一个临时应用,不应该以原始意图启动,而应调整意图,使其看起来像正常的即时应用程序启动
    if (componentSpecified
            && !(Intent.ACTION_VIEW.equals(intent.getAction()) && intent.getData() == null)
            && !Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE.equals(intent.getAction())
            && !Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE.equals(intent.getAction())
            && mService.getPackageManagerInternalLocked()
                    .isInstantAppInstallerComponent(intent.getComponent())) {
        // intercept intents targeted directly to the ephemeral installer the
        // ephemeral installer should never be started with a raw Intent; instead
        // adjust the intent so it looks like a "normal" instant app launch
        intent.setComponent(null /*component*/);
        componentSpecified = false;
    }

    //查询与intent匹配的Activity,rInfo中包含了查找信息;
    //mSupervisor.resolveIntent()会调用PKMS方法获取该Activity的信息
    ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
            0 /* matchFlags */,
                    computeResolveFilterUid(
                            callingUid, realCallingUid, mRequest.filterCallingUid));
    if (rInfo == null) {
        UserInfo userInfo = mSupervisor.getUserInfo(userId);
        if (userInfo != null && userInfo.isManagedProfile()) {
            UserManager userManager = UserManager.get(mService.mContext);
            boolean profileLockedAndParentUnlockingOrUnlocked = false;
            long token = Binder.clearCallingIdentity();
            try {
                UserInfo parent = userManager.getProfileParent(userId);
                profileLockedAndParentUnlockingOrUnlocked = (parent != null)
                        && userManager.isUserUnlockingOrUnlocked(parent.id)
                        && !userManager.isUserUnlockingOrUnlocked(userId);
            } finally {
                Binder.restoreCallingIdentity(token);
            }
            if (profileLockedAndParentUnlockingOrUnlocked) {
                rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId,
                        PackageManager.MATCH_DIRECT_BOOT_AWARE
                                | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
                        computeResolveFilterUid(
                                callingUid, realCallingUid, mRequest.filterCallingUid));
            }
        }
    }

    //从rInfo中得到aInfo,aInfo表示运行时的Activity信息
    ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);

    synchronized (mService) {
        final ActivityStack stack = mSupervisor.mFocusedStack;
        //是否需要修改Configuration信息,此处为false
        stack.mConfigWillChange = globalConfig != null
                && mService.getGlobalConfiguration().diff(globalConfig) != 0;
        if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
                "Starting activity when config will change = " + stack.mConfigWillChange);

        final long origId = Binder.clearCallingIdentity();

        //下面是判断该Acitivity是否是一个重量级的进程;
        /*FLAG_CANT_SAVE_STATE由AndroidManifest.xml的Application标签指定,该标签并未对SDK开放;
        系统中只有development/samples/HeavyWeight这一个示例应用使用到,因此,这个判断可以忽略掉*/
        if (aInfo != null &&
                (aInfo.applicationInfo.privateFlags
                        & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0 &&
                mService.mHasHeavyWeightFeature) {
            ............        
        }

        final ActivityRecord[] outRecord = new ActivityRecord[1];
        //将请求发送给startActivity()去执行,返回启动结果
        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);

        Binder.restoreCallingIdentity(origId);

        //更新Configuration
        if (stack.mConfigWillChange) {
   mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
                    "updateConfiguration()");
            stack.mConfigWillChange = false;
            if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
                    "Updating to new configuration after starting activity.");
            mService.updateConfigurationLocked(globalConfig, null, false);
        }

        //此例传入的outResult为null,不执行这步;
        // 只有调用ActivityManagerService的startActivityAndWait方法时,传入的outResult参数不为null,
        //但startActivityAndWait方法只在通过am start-W启动Activity的时候用到。-W的意思是wait*/
        if (outResult != null) {
        	............
        }

        mSupervisor.getActivityMetricsLogger().notifyActivityLaunched(res, outRecord[0]);
        return res;
    }
}

点评:startActivityMayWait方法的主要工作如下:

①调用mSupervisor.resolveIntent方法经由PackageManagerService查询系统中是否存在处理指定Intent的Activity,即找到Settings;

②根据caller判断启动Activity的客户端是应用程序还是其他进程(如adb shell);

③处理FLAG_CANT_SAVE_STATE标记,该标记目前只在示例程序中使用;

④继续调用ActivityStarter.startActivity执行后续操作;

⑤处理Configuration需要改变的情况,对于启动Settings应用,则不需要改变;

⑥处理wait状态,正常启动应用程序不需要执行这个步骤,此例中startActivityMayWait其实是startActivity" Not" Wait;

startActivityMayWait启动Activity的后续工作放在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) {

    //启动理由不能为null
    if (TextUtils.isEmpty(reason)) {
        throw new IllegalArgumentException("Need to specify a reason.");
    }
    mLastStartReason = reason;
    mLastStartActivityTimeMs = System.currentTimeMillis();
    mLastStartActivityRecord[0] = null;

    //又调用startActivity()方法
    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);

    if (outActivity != null) {
        // mLastStartActivityRecord[0] is set in the call to startActivity above.
        outActivity[0] = mLastStartActivityRecord[0];
    }

    return getExternalResult(mLastStartActivityResult);
}

继续调用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, boolean allowPendingRemoteAnimationRegistryLookup) {
    int err = ActivityManager.START_SUCCESS;
    // Pull the optional Ephemeral Installer-only bundle out of the options early.
    final Bundle verificationBundle
            = options != null ? options.popAppVerificationBundle() : null;

    ProcessRecord callerApp = null;
    //caller是Launcher所在的应用程序进程的ApplicationThread对象
    if (caller != null) {
        //得到代表Launcher进程的callerApp对象,它是ProcessRecord类型,ProcessRecord用于描述一种应用程序进程
        callerApp = mService.getRecordForAppLocked(caller);
        if (callerApp != null) {
            //获取Launcher进程的pid和uid
            callingPid = callerApp.pid;
            callingUid = callerApp.info.uid;
        } else {
            err = ActivityManager.START_PERMISSION_DENIED;
        }
    }

    final int userId = aInfo != null && aInfo.applicationInfo != null
            ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;

    ActivityRecord sourceRecord = null;
    ActivityRecord resultRecord = null;
    //传入的resultTo代表Launcher
    if (resultTo != null) {
        取出Launcher的ActivityRecord
        sourceRecord = mSupervisor.isInAnyStackLocked(resultTo);
        if (sourceRecord != null) {
            /*传入的requestCode为-1,即不需要返回结果。对于需要返回结果的情况,发起startActivity的一方便是接收返回结果的一方(只要其状态不是finishing)。
            只有调用startActivityForResult时,传入的参数requestCode>=0才会接收返回结果*/
            if (requestCode >= 0 && !sourceRecord.finishing) {
                resultRecord = sourceRecord;
            }
        }
    }

    final int launchFlags = intent.getFlags();

    //获取Intent存储的启动标记flag,处理FLAG_ACTIVITY_FORWARD_RESULT标记,我们没有设置此标记
    if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) {
        if (requestCode >= 0) {
            SafeActivityOptions.abort(options);
            return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
        }
        resultRecord = sourceRecord.resultTo;
        if (resultRecord != null && !resultRecord.isInStackLocked()) {
            resultRecord = null;
        }
        resultWho = sourceRecord.resultWho;
        requestCode = sourceRecord.requestCode;
        sourceRecord.resultTo = null;
        if (resultRecord != null) {
            resultRecord.removeResultsLocked(sourceRecord, resultWho, requestCode);
        }
        if (sourceRecord.launchedFromUid == callingUid) {
            callingPackage = sourceRecord.launchedFromPackage;
        }
    }
    
    if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
        err = ActivityManager.START_INTENT_NOT_RESOLVED;
    }

    if (err == ActivityManager.START_SUCCESS && aInfo == null) {
        err = ActivityManager.START_CLASS_NOT_FOUND;
    }

    //Activity作为语音会话的一部分启动,这个暂时没讨论
    if (err == ActivityManager.START_SUCCESS && sourceRecord != null
            && sourceRecord.getTask().voiceSession != null) {
       ............
    }

    //关于语音的,先pass
    if (err == ActivityManager.START_SUCCESS && voiceSession != null) {
        ............
    }

    final ActivityStack resultStack = resultRecord == null ? null : resultRecord.getStack();

    if (err != START_SUCCESS) {
        /*指定了接收启动结果的Activity,通过sendActivityResultLocked将错误结果返回,该错误结果为RESULT_CANCELED*/
        if (resultRecord != null) {
            resultStack.sendActivityResultLocked(
                    -1, resultRecord, resultWho, requestCode, RESULT_CANCELED, null);
        }
        SafeActivityOptions.abort(options);
        return err;
    }

    //检查是否有启动Activity的权限*/
    boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
            requestCode, callingPid, callingUid, callingPackage, ignoreTargetSecurity,
            inTask != null, callerApp, resultRecord, resultStack);
    abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
            callingPid, resolvedType, aInfo.applicationInfo);

    // Merge the two options bundles, while realCallerOptions takes precedence.
    ActivityOptions checkedOptions = options != null
            ? options.getOptions(intent, aInfo, callerApp, mSupervisor)
            : null;
    if (allowPendingRemoteAnimationRegistryLookup) {
        checkedOptions = mService.getActivityStartController()
                .getPendingRemoteAnimationRegistry()
                .overrideOptionsIfNeeded(callingPackage, checkedOptions);
    }

    ///Add for application lock start
    //为应用程序锁定启动添加
    if (mService.mAppsLockOps != null) {

        int result = mService.mAppsLockOps.isPackageNeedLocked(
                aInfo.applicationInfo.packageName,
                aInfo.name,
                mService.isSleepingLocked(),
                userId);

        if (result == GomeApplicationsLockOps.APPLICATION_LOCK_SHOULD_LOCK) {
            Intent watchIntent = (Intent) intent.clone();
            Bundle bOption = null;

            if(checkedOptions != null) {
                bOption = checkedOptions.toBundle();
            }
            if (mService.showAccessOnTopRunningActivity(watchIntent,
                    aInfo.applicationInfo.packageName,
                    userId, requestCode, resultWho, bOption, caller, mLastStartReason)) {
                ActivityOptions.abort(checkedOptions);
                return ActivityManager.START_SUCCESS;
            }
        }
    }
    ///Add for application lock end

    //IActivityController是AMS的监听器,我们这里没有设置
    if (mService.mController != null) {
        try {
            // The Intent we give to the watcher has the extra data
            // stripped off, since it can contain private information.
            Intent watchIntent = intent.cloneFilter();
            //决定是否启动当前请求启动的Activity
            abort |= !mService.mController.activityStarting(watchIntent,
                    aInfo.applicationInfo.packageName);
        } catch (RemoteException e) {
            mService.mController = null;
        }
    }

    mInterceptor.setStates(userId, realCallingPid, realCallingUid, startFlags, callingPackage);
    if (mInterceptor.intercept(intent, rInfo, aInfo, resolvedType, inTask, callingPid,
            callingUid, checkedOptions)) {
        intent = mInterceptor.mIntent;
        rInfo = mInterceptor.mRInfo;
        aInfo = mInterceptor.mAInfo;
        resolvedType = mInterceptor.mResolvedType;
        inTask = mInterceptor.mInTask;
        callingPid = mInterceptor.mCallingPid;
        callingUid = mInterceptor.mCallingUid;
        checkedOptions = mInterceptor.mActivityOptions;
    }

    if (abort) {
        if (resultRecord != null) {
            resultStack.sendActivityResultLocked(-1, resultRecord, resultWho, requestCode,
                    RESULT_CANCELED, null);
        }
        ActivityOptions.abort(checkedOptions);
        return START_ABORTED;
    }

    if (mService.mPermissionReviewRequired && aInfo != null) {
        if (mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
                aInfo.packageName, userId)) {
            IIntentSender target = mService.getIntentSenderLocked(
                    ActivityManager.INTENT_SENDER_ACTIVITY, callingPackage,
                    callingUid, userId, null, null, 0, new Intent[]{intent},
                    new String[]{resolvedType}, PendingIntent.FLAG_CANCEL_CURRENT
                            | PendingIntent.FLAG_ONE_SHOT, null);

            final int flags = intent.getFlags();
            Intent newIntent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
            newIntent.setFlags(flags
                    | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            newIntent.putExtra(Intent.EXTRA_PACKAGE_NAME, aInfo.packageName);
            newIntent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
            if (resultRecord != null) {
                newIntent.putExtra(Intent.EXTRA_RESULT_NEEDED, true);
            }
            intent = newIntent;

            resolvedType = null;
            callingUid = realCallingUid;
            callingPid = realCallingPid;

            rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId, 0,
                    computeResolveFilterUid(
                            callingUid, realCallingUid, mRequest.filterCallingUid));
            aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags,
                    null /*profilerInfo*/);
        }
    }

    if (rInfo != null && rInfo.auxiliaryInfo != null) {
        intent = createLaunchIntent(rInfo.auxiliaryInfo, ephemeralIntent,
                callingPackage, verificationBundle, resolvedType, userId);
        resolvedType = null;
        callingUid = realCallingUid;
        callingPid = realCallingPid;

        aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, null /*profilerInfo*/);
    }

    //创建即将要启动的Activity即Settings的描述类ActivityRecord;
    //同ProcessRecord一样,ActivityRecord用来描述一个Activity,用来记录一个Activity的所有信息
    ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
            callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
            resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
            mSupervisor, checkedOptions, sourceRecord);
    if (outActivity != null) {
        //将ActivityRecord赋值给outActivity
        outActivity[0] = r;
    }

    if (r.appTimeTracker == null && sourceRecord != null) {
        r.appTimeTracker = sourceRecord.appTimeTracker;
    }

    //获取当前正在显示的ActivityStack,这里指的是Launcher所在的ActivityStack
    final ActivityStack stack = mSupervisor.mFocusedStack;

    //stack.getResumedActivity()表示当前处于resume状态的Activity,即当前正在显示的Activity,由于是从Launcher启动一个程序的,
    //此时该程序还没有启动,这里stack.getResumedActivity()依然是Launcher
    if (voiceSession == null && (stack.getResumedActivity() == null
            || stack.getResumedActivity().info.applicationInfo.uid != realCallingUid)) {//不成立
        //如果没有当前正在显示的Activity,有理由怀疑发起startActivity的进程此时是否能够切换Activity;
        //这种情况通常发生在startActivity发起方进入pause/stop/destroy方法时,此时要暂停切换Activity
        if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid,
                realCallingPid, realCallingUid, "Activity start")) {
            //如果没有权限,则将启动请求存入mPendingActivityLaunches后返回
            mController.addPendingActivityLaunch(new PendingActivityLaunch(r, sourceRecord, startFlags, stack, callerApp));
            ActivityOptions.abort(checkedOptions);
            return ActivityManager.START_SWITCHES_CANCELED;
        }
    }

    //mDidAppSwitch为true
    if (mService.mDidAppSwitch) {
        mService.mAppSwitchesAllowedTime = 0;
    } else {
        mService.mDidAppSwitch = true;
    }

    /*启动 mPendingActivityLaunches中存储的待启动Activity*/
    mController.doPendingActivityLaunches(false);

    //继续调用startActivity()方法
    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();
        //调用startActivityUnchecked()方法
        result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
                startFlags, doResume, options, inTask, outActivity);
    } finally {
        final ActivityStack stack = mStartActivity.getStack();
        if (!ActivityManager.isStartResultSuccessful(result) && stack != null) {
            stack.finishActivityLocked(mStartActivity, RESULT_CANCELED,
                    null /* intentResultData */, "startActivity", true /* oomAdj */);
        }
        mService.mWindowManager.continueSurfaceLayout();
    }

    //startActivityUnchecked结束后,做最后的Settings启动处理
    postStartActivityProcessing(r, result, mTargetStack);

    return result;
}

点评:ProcessRecord维护一个activities的列表,用于存储运行在该进程的Activity的ActivityRecord,比如com.android.launcher2.Launcher。应用程序本身都在AMS的管理范围中,对于由应用程序 发起的startActivity,都可以在AMS中找到其对应的ProcessRecord,这样可以确保调用方的权限匹配正确;

上述代码的工作可以归纳如下:

①各种检查:检查调用方的权限、检查调用方是否需要返回结果、检查FLAG_ACTIVITY_FORWARD_RESULT标记、检查Intent是否正确、检查目标Activity是否存在、检查是否有startActivity权限、检查当前能否切换Activity;

②检查通过后,创建目标Activity的ActivityRecord;

③将请求转发给startActivityUncheckedLocked方法,此时处于mPendingActivityLaunches列表中的待启动Activity将被优先处理。

由此可见,startActivityUncheckedLocked方法签名中Unchecked的意思是:经过这么多检查(check),终于不需要检查(uncheck)了。

 

继续来看startActivityUncheckedLocked()方法:

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
        ActivityRecord[] outActivity) {

    //初始化ActivityStarter的状态,如mLaunchMode ,mLaunchFlags ,并且处理一些intent的常用标签
    setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,voiceInteractor);

    //用来处理Settings的启动模式,并将启动方案添加在mLaunchFlags中
    computeLaunchingTaskFlags();

    //初始化mSourceStack,也就是Launcher的AcitivityStack
    computeSourceStack();

    .........
}

startActivityUncheckedLocked()的方法比较长,先看这几个方法:

①setInitialState()

private void setInitialState(ActivityRecord r, ActivityOptions options, TaskRecord inTask,
        boolean doResume, int startFlags, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
    reset(false /* clearRequest */);

    mStartActivity = r;
    mIntent = r.intent;
    mOptions = options;
    mCallingUid = r.launchedFromUid;
    mSourceRecord = sourceRecord;
    mVoiceSession = voiceSession;
    mVoiceInteractor = voiceInteractor;

    mPreferredDisplayId = getPreferedDisplayId(mSourceRecord, mStartActivity, options);

    mLaunchParams.reset();

    mSupervisor.getLaunchParamsController().calculate(inTask, null /*layout*/, r, sourceRecord,
            options, mLaunchParams);

    //activity的启动模式
    mLaunchMode = r.launchMode;

    mLaunchFlags = adjustLaunchFlagsToDocumentMode(
            r, LAUNCH_SINGLE_INSTANCE == mLaunchMode,
            LAUNCH_SINGLE_TASK == mLaunchMode, mIntent.getFlags());
    mLaunchTaskBehind = r.mLaunchTaskBehind
            && !isLaunchModeOneOf(LAUNCH_SINGLE_TASK, LAUNCH_SINGLE_INSTANCE)
            && (mLaunchFlags & FLAG_ACTIVITY_NEW_DOCUMENT) != 0;

    sendNewTaskResultRequestIfNeeded();

    if ((mLaunchFlags & FLAG_ACTIVITY_NEW_DOCUMENT) != 0 && r.resultTo == null) {
        mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
    }

    if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
        if (mLaunchTaskBehind
                || r.info.documentLaunchMode == DOCUMENT_LAUNCH_ALWAYS) {
            mLaunchFlags |= FLAG_ACTIVITY_MULTIPLE_TASK;
        }
    }

    //我们没有设置FLAG_ACTIVITY_NO_USER_ACTION标签,mSupervisor.mUserLeaving为true
    mSupervisor.mUserLeaving = (mLaunchFlags & FLAG_ACTIVITY_NO_USER_ACTION) == 0;
    if (DEBUG_USER_LEAVING) Slog.v(TAG_USER_LEAVING,
            "startActivity() => mUserLeaving=" + mSupervisor.mUserLeaving);

    //doResume表示立刻启动,我们传进来的doResume为true
    mDoResume = doResume;
    if (!doResume || !r.okToShowLocked()) {
        r.delayedResume = true;
        mDoResume = false;
    }

    //关于activity动画的,先忽略
    if (mOptions != null) {
       ......
    }

    //没有设置FLAG_ACTIVITY_PREVIOUS_IS_TOP标签,所以mNotTop为true
    mNotTop = (mLaunchFlags & FLAG_ACTIVITY_PREVIOUS_IS_TOP) != 0 ? r : null;

    //目标Activity的TaskRecord,这里为null
    mInTask = inTask;

    if (inTask != null && !inTask.inRecents) {
        Slog.w(TAG, "Starting activity in task not in recents: " + inTask);
        mInTask = null;
    }

    mStartFlags = startFlags;

    //未设置START_FLAG_ONLY_IF_NEEDED标签
    if ((startFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
        ActivityRecord checkedCaller = sourceRecord;
        if (checkedCaller == null) {
            checkedCaller = mSupervisor.mFocusedStack.topRunningNonDelayedActivityLocked(
                    mNotTop);
        }
        if (!checkedCaller.realActivity.equals(r.realActivity)) {
            // Caller is not the same as launcher, so always needed.
            mStartFlags &= ~START_FLAG_ONLY_IF_NEEDED;
        }
    }

    //mNoAnimation为false
    mNoAnimation = (mLaunchFlags & FLAG_ACTIVITY_NO_ANIMATION) != 0;
}

 

点评:该方法是用来初始化ActivityStarter的状态,如mLaunchMode ,mLaunchFlags ,并且处理intent的一些标签,这些标签常用的有:

FLAG_ACTIVITY_NO_USER_ACTION;

FLAG_ACTIVITY_PREVIOUS_IS_TOP;

FLAG_ACTIVITY_NO_ANIMATION;

我们来分析下FLAG_ACTIVITY_NO_USER_ACTION标签,这个标签有啥用呢?

它与Activity的生命周期有关,用于判断是否是用户行为导致Activity切换。例如当用户按Home键时,当前Activity切换到后台,此时会回调当前Activity生命周期的onUserLeaveHint方法;但如果是来电导致当前Activity切换到后台,则不会回调当前Activity生命周期的onUserLeaveHint方法。

若在启动Activity的Intent中设置了FLAG_ACTIVITY_NO_USER_ACTION标记,则表明当前启动行为是非用户行为,这样被切换到后台的Activity便不会回调onUserLeaveHint方法。

②computeLaunchingTaskFlags()

private void computeLaunchingTaskFlags() {
    if (mSourceRecord == null && mInTask != null && mInTask.getStack() != null) {
        //由于mSourceRecord != null,这个判断不成立,
        //不是由Activity发出的启动请求,如系统启动Launcher的过程-->mSourceRecord == null,
        ............
    } else {
        mInTask = null;
        if ((mStartActivity.isResolverActivity() || mStartActivity.noDisplay) && mSourceRecord != null
                && mSourceRecord.inFreeformWindowingMode())  {
            mAddingToTask = true;
        }
    }

    if (mInTask == null) {
        if (mSourceRecord == null) {//不成立
            if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) == 0 && mInTask == null) {
                mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
            }
        } else if (mSourceRecord.launchMode == LAUNCH_SINGLE_INSTANCE) {
            //如果Launcher的启动模式是SingleInstance,那就需要新建一个Task,本例中Launcher的启动模式是SingleTask
            mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
        } else if (isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {
            //如果Settings的启动模式是SingleInstance或SingleTask,那就需要新建一个Task,本例中Settings的启动模式是SingleTask
            mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
        }
    }
}

点评:这个方法是用来处理Settings的启动模式,并将启动方案添加在mLaunchFlags中;

关于FLAG_ACTIVITY_NEW_TASK标签,该标签是用来确定待启动Activity是否需要运行于新的Task;

需要在新的Task中运行Activity的条件有以下3种:

1)sourceRecord为null,即不是由Activity发出的启动请求,例如启动Launcher或者通过adb start启动指定Activity;

2)sourceRecord,也就是Launcher的启动模式为singleInstance;

3)要启动的目标Activity,也就是Settings的启动模式为singleInstance或者singleTask。

其中,当3)中的Settings启动模式为singleTask时,如果Settings要运行的Task已经存在,那它就运行在那个已经创建出来的Task中,并不会重新创建一个新的Task;

③computeSourceStack()

初始化mSourceStack,也就是Launcher的ActivityStack;

 

继续分析startActivityUncheckedLocked():

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
        ActivityRecord[] outActivity) {

    //初始化ActivityStarter的状态,如mLaunchMode ,mLaunchFlags ,并且处理一些intent的常用标签
    setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
            voiceInteractor);

    //用来处理Settings的启动模式,并将启动方案添加在mLaunchFlags中
    computeLaunchingTaskFlags();

    //初始化mSourceStack,也就是Launcher的AcitivityStack
    computeSourceStack();

    //将调整后的mLaunchFlags设置给mIntent
    mIntent.setFlags(mLaunchFlags);

    //查找是否有可复用的Task以及Activity,本例中的reusedActivity为null,表示没有可复用的Task以及Activity
    ActivityRecord reusedActivity = getReusableIntentActivity();

    ............
    ............

    //本例中的reusedActivity为null
    if (reusedActivity != null) {
        //虽然本例中的reusedActivity为null,但我们假设一下,reusedActivity为true;
        if (mService.getLockTaskController().isLockTaskModeViolation(reusedActivity.getTask(),
                (mLaunchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))
                        == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))) {
            Slog.e(TAG, "startActivityUnchecked: Attempt to violate Lock Task Mode");
            return START_RETURN_LOCK_TASK_MODE_VIOLATION;
        }

        final boolean clearTopAndResetStandardLaunchMode =
                (mLaunchFlags & (FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED))
                        == (FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
                && mLaunchMode == LAUNCH_MULTIPLE;//false

        //将可复用的栈赋给Settings,这样他们就共处一个栈了
        if (mStartActivity.getTask() == null && !clearTopAndResetStandardLaunchMode) {//成立
            mStartActivity.setTask(reusedActivity.getTask());
        }

        if (reusedActivity.getTask().intent == null) {
            reusedActivity.getTask().setIntent(mStartActivity);
        }

        if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0
                || isDocumentLaunchesIntoExisting(mLaunchFlags)
                || isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {//成立
            final TaskRecord task = reusedActivity.getTask();
            //在栈中寻找,Settings是否之前就已经存在于栈中,如果已经存在的话,就将此栈中在Settings之前的Activity全部从栈中移除,返回的top就是之前就已经存在于栈中的Settings;
            //现在Settings已经处于栈顶了
            final ActivityRecord top = task.performClearTaskForReuseLocked(mStartActivity,
                    mLaunchFlags);
            if (reusedActivity.getTask() == null) {
                reusedActivity.setTask(task);
            }

            if (top != null) {//成立
                if (top.frontOfTask) {
                    top.getTask().setIntent(mStartActivity);
                }
                //调用activity的onNewIntent()方法,这个属于AMS与ActivityThread交互的范畴,暂时不讨论
                deliverNewIntent(top);
            }
        }

        mSupervisor.sendPowerHintForLaunchStartIfNeeded(false /* forceSend */, reusedActivity);

        reusedActivity = setTargetStackAndMoveToFrontIfNeeded(reusedActivity);

        final ActivityRecord outResult =
                outActivity != null && outActivity.length > 0 ? outActivity[0] : null;
        if (outResult != null && (outResult.finishing || outResult.noDisplay)) {
            outActivity[0] = reusedActivity;
        }

        if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
            resumeTargetStackIfNeeded();
            return START_RETURN_INTENT_TO_CALLER;
        }

        if (reusedActivity != null) {
            setTaskFromIntentActivity(reusedActivity);

            if (!mAddingToTask && mReuseTask == null) {
                resumeTargetStackIfNeeded();
                if (outActivity != null && outActivity.length > 0) {
                    outActivity[0] = reusedActivity;
                }

                return mMovedToFront ? START_TASK_TO_FRONT : START_DELIVERED_TO_TOP;
            }
        }
    }
    ............
    ............
}

点评:我们再来看这部分代码,这部分的代码的意思是,检查是否有可复用的Task或者Activity;

①通过getReusableIntentActivity()方法来检查是否有可复用的Task或者Activity;

②如果有可复用的Task或者Activity,并且有下面3个启动标签中的一个:FLAG_ACTIVITY_CLEAR_TOP,LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK,那就在栈中寻找,Settings是否之前就已经存在于栈中,如果已经存在的话,就将Settings之前的Activity全部从栈中移除,并调用Settings的onNewIntent()方法;

由于getReusableIntentActivity()的代码牵扯到affinity,所以我们得分析下它的代码:

private ActivityRecord getReusableIntentActivity() {
    //本例的putIntoExistingTask 为true
    boolean putIntoExistingTask = ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0 &&
            (mLaunchFlags & FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
            || isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK);
    putIntoExistingTask &= mInTask == null && mStartActivity.resultTo == null;//成立,putIntoExistingTask为true
    ActivityRecord intentActivity = null;
    if (mOptions != null && mOptions.getLaunchTaskId() != -1) {//不成立
        final TaskRecord task = mSupervisor.anyTaskForIdLocked(mOptions.getLaunchTaskId());
        intentActivity = task != null ? task.getTopActivity() : null;
    } else if (putIntoExistingTask) {
        if (LAUNCH_SINGLE_INSTANCE == mLaunchMode) {//不成立
           intentActivity = mSupervisor.findActivityLocked(mIntent, mStartActivity.info,
                   mStartActivity.isActivityTypeHome());
        } else if ((mLaunchFlags & FLAG_ACTIVITY_LAUNCH_ADJACENT) != 0) {//不成立
            intentActivity = mSupervisor.findActivityLocked(mIntent, mStartActivity.info,
                    !(LAUNCH_SINGLE_TASK == mLaunchMode));
        } else {//成立
            intentActivity = mSupervisor.findTaskLocked(mStartActivity, mPreferredDisplayId);
        }
    }
    return intentActivity;
}

点评:从上面代码可以看出,当满足以下任何一个条件,需要判断是否有可复用的Task:

1)在启动标记中设置了FLAG_ACTIVITY_NEW_TASK且未设置FLAG_ACTIVITY_MULTIPLE_TASK;

 2)要启动的目标Activity的启动模式为singleTask或者为singleInstance;

可复用Task的匹配原则如下:

原则1:当要启动的目标Activity的启动模式非singleInstance时,遵循findTaskLocked方法的匹配规则;

原则2:当要启动的目标Activity的启动模式为singleInstance时,遵循findActivityLocked方法的匹配 规则;

我们着重分析原则1,即mSupervisor.findTaskLocked()函数:

ActivityRecord findTaskLocked(ActivityRecord r, int displayId) {
    mTmpFindTaskResult.r = null;
    mTmpFindTaskResult.matchedByRootAffinity = false;
    ActivityRecord affinityMatch = null;
    //遍历所有的显示屏幕
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        final ActivityDisplay display = mActivityDisplays.valueAt(displayNdx);
        //遍历屏幕里所有的ActivityStack 
        for (int stackNdx = display.getChildCount() - 1; stackNdx >= 0; --stackNdx) {
            final ActivityStack stack = display.getChildAt(stackNdx);
            if (!r.hasCompatibleActivityType(stack)) {
                continue;
            }
            //调用ActivityStack.findTaskLocked(),返回结果在mTmpFindTaskResult中
            stack.findTaskLocked(r, mTmpFindTaskResult);
            if (mTmpFindTaskResult.r != null) {
                if (!mTmpFindTaskResult.matchedByRootAffinity) {
                    return mTmpFindTaskResult.r;
                } else if (mTmpFindTaskResult.r.getDisplayId() == displayId) {
                    affinityMatch = mTmpFindTaskResult.r;
                } else if (DEBUG_TASKS && mTmpFindTaskResult.matchedByRootAffinity) {
                }
            }
        }
    }
    return affinityMatch;
}

继续看stack.findTaskLocked(r, mTmpFindTaskResult):

void findTaskLocked(ActivityRecord target, FindTaskResult result) {
        Intent intent = target.intent;
        ActivityInfo info = target.info;
        //获取到ComponentName
        ComponentName cls = intent.getComponent();
        if (info.targetActivity != null) {
            cls = new ComponentName(info.packageName, info.targetActivity);
        }
        final int userId = UserHandle.getUserId(info.applicationInfo.uid);
        boolean isDocument = intent != null & intent.isDocument();//isDocument为false
        // If documentData is non-null then it must match the existing task data.
        Uri documentData = isDocument ? intent.getData() : null;//documentData为null

        if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Looking for task of " + target + " in " + this);
        //遍历ActivityStack中所有的TaskRecord
        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
            //得到task
            final TaskRecord task = mTaskHistory.get(taskNdx);
            if (task.voiceSession != null) {
                // We never match voice sessions; those always run independently.
                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": voice session");
                continue;
            }
            if (task.userId != userId) {
                // Looking for a different task.
                if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Skipping " + task + ": different user");
                continue;
            }

            // Overlays should not be considered as the task's logical top activity.
            //从task的顶部开始寻找,找到第一个没有被finish的ActivityRecord
            final ActivityRecord r = task.getTopActivity(false /* includeOverlays */);
            if (r == null || r.finishing || r.userId != userId ||
                    r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
                continue;
            }
            if (!r.hasCompatibleActivityType(target)) {
                continue;
            }

            //得到Task的intent,taskIntent值得是启动这个任务栈的intent
            final Intent taskIntent = task.intent;
            //得到Task的affinity
            final Intent affinityIntent = task.affinityIntent;
            final boolean taskIsDocument;
            final Uri taskDocumentData;
            if (taskIntent != null && taskIntent.isDocument()) {//不成立
                taskIsDocument = true;
                taskDocumentData = taskIntent.getData();
            } else if (affinityIntent != null && affinityIntent.isDocument()) {//不成立
                taskIsDocument = true;
                taskDocumentData = affinityIntent.getData();
            } else {//成立
                taskIsDocument = false;
                taskDocumentData = null;
            }

            if (taskIntent != null && taskIntent.getComponent() != null &&
                    taskIntent.getComponent().compareTo(cls) == 0 &&
                    Objects.equals(documentData, taskDocumentData)) {
                //查看Task的Intent是否与要启动的目标Activity有相同的Component,如果有则返回该ActivityRecord
                result.r = r;
                result.matchedByRootAffinity = false;
                break;
            } else if (affinityIntent != null && affinityIntent.getComponent() != null &&
                    affinityIntent.getComponent().compareTo(cls) == 0 &&
                    Objects.equals(documentData, taskDocumentData)) {
                //查看Task的affinityIntent是否与要启动的目标Activity有相同的Component,如果有则返回该ActivityRecord
                result.r = r;
                result.matchedByRootAffinity = false;
                break;
            } else if (!isDocument && !taskIsDocument
                    && result.r == null && task.rootAffinity != null) {
                if (task.rootAffinity.equals(target.taskAffinity)) {
                    //Task的affinity是否与要启动的目标Activity的affinity相同,如果有则返回该ActivityRecord
                    result.r = r;
                    result.matchedByRootAffinity = true;
                }
            } else if (DEBUG_TASKS) Slog.d(TAG_TASKS, "Not a match: " + task);
        }
    }

从上面可以总结下,可复用Task的匹配规则如下:

1)当要启动的目标Activity的启动模式非singleInstance 时:

遍历mHistory中的ActivityRecord,查看该ActivityRecord所属Task的affinity是否与要启动的目标Activity的affinity相同,如果有则返回该ActivityRecord;

遍历mHistory中的ActivityRecord,查看该ActivityRecord所属Task的Intent是否与要启动的目标Activity有相同的Component,如果有则返回该ActivityRecord;

遍历mHistory中的ActivityRecord,查看该ActivityRecord所属Task的affinityIntent是否与要启动的目标Activity有相同的Component, 如果有则返回该ActivityRecord;

2)当要启动的目标Activity的启动模式为singleInstance时:

遍历mHistory中的ActivityRecord,查看该ActivityRecord所属Task的Intent是否与要启动的目标Activity有相同的Component,如果有则返回该ActivityRecord。

关于taskAffinity:我们可以在AndroidManifest.xml中设置android:taskAffinity,用来指定Activity希望归属的栈,在默认情况下,同一个应用程序的所有的Activity都有着相同的taskAffinity,taskAffinity在下面两种情况下会产生效果:

1)taskAffinity与FLAG_ACTIVITY_NEW_TASK或者singleTask配合,如果新启动的Activity的taskAffinity和栈的taskAffinity相同则加入到该栈;如果不同,就会创建新栈;

2)taskAffinity与allowTaskReparenting配合,如果allowTaskReparenting为true,说明Activity具有转移的能力;

 

接下来继续分析startActivityUnchecked()的代码:

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
        ActivityRecord[] outActivity) {
    ............
    ............
    if (mStartActivity.packageName == null) {
        final ActivityStack sourceStack = mStartActivity.resultTo != null
                ? mStartActivity.resultTo.getStack() : null;
        if (sourceStack != null) {
            sourceStack.sendActivityResultLocked(-1 /* callingUid */, mStartActivity.resultTo,
                    mStartActivity.resultWho, mStartActivity.requestCode, RESULT_CANCELED,
                    null /* data */);
        }
        ActivityOptions.abort(mOptions);
        return START_CLASS_NOT_FOUND;
    }

    //如果要启动的目标Activity与当前栈顶正在显示的Activity相同,需要检查该Activity是否只需要启动一次。
    //topStack是正在显示的Activity栈
    final ActivityStack topStack = mSupervisor.mFocusedStack;
    final ActivityRecord topFocused = topStack.getTopActivity();
    //本例的top为Launcher
    final ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(mNotTop);
    //要启动的目标Activity与当前栈顶正在显示的Activity相同,activity的启动标签为FLAG_ACTIVITY_SINGLE_TOP或者启动模式为singTop与SingleTask之一;
    //满足上述情况,dontStart就为true,表示不需要重新启动Activity,直接调用Activity的onNewActivity()方法即可
    final boolean dontStart = top != null && mStartActivity.resultTo == null
            && top.realActivity.equals(mStartActivity.realActivity)
            && top.userId == mStartActivity.userId
            && top.app != null && top.app.thread != null
            && ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0
            || isLaunchModeOneOf(LAUNCH_SINGLE_TOP, LAUNCH_SINGLE_TASK));
    if (dontStart) {//本例的dontStart为false
        //我们假想,dontStart为false
        topStack.mLastPausedActivity = null;
        if (mDoResume) {
            mSupervisor.resumeFocusedStackTopActivityLocked();
        }
        ActivityOptions.abort(mOptions);
        if ((mStartFlags & START_FLAG_ONLY_IF_NEEDED) != 0) {
            return START_RETURN_INTENT_TO_CALLER;
        }

        //调用activity的onNewActivity()方法,这是IPC部分的,后面分析
        deliverNewIntent(top);

        mSupervisor.handleNonResizableTaskIfNeeded(top.getTask(), preferredWindowingMode,
                preferredLaunchDisplayId, topStack);

        return START_DELIVERED_TO_TOP;
    }

    ............
    ............
}

点评:startActivityUnchecked()方法执行到这里,都是在判断是否需要新启动一个Task或者新启动一个Activity,本例中我们是需要新启动一个Task或者一个Activity的,那继续看startActivityUnchecked()方法:

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
        ActivityRecord[] outActivity) {
............
............
    boolean newTask = false;
    final TaskRecord taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
            ? mSourceRecord.getTask() : null;

    int result = START_SUCCESS;
    if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
            && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {//条件成立
        newTask = true;
        //创建一个新的TaskRecord,并将新创建的TaskRecord与ActivityRecord进行关联,即每个Activity会存储其所处的Task
        result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack);
    } else if (mSourceRecord != null) {
        result = setTaskFromSourceRecord();
    } else if (mInTask != null) {
        result = setTaskFromInTask();
    } else {
        setTaskToCurrentTopOrCreateNewTask();
    }
    if (result != START_SUCCESS) {
        return result;
    }
    ............
    ............
}

点评:上面代码的主要用途就是用来创建TaskRecord,来分析下setTaskFromReuseOrCreateNewTask()方法:

private int setTaskFromReuseOrCreateNewTask(
        TaskRecord taskToAffiliate, ActivityStack topStack) {
    //得到ActivityStack
    mTargetStack = computeStackFocus(mStartActivity, true, mLaunchFlags, mOptions);

    if (mReuseTask == null) {//满足
        //创建TaskRecord,其中taskId,就是TaskRecord的唯一标识符;
        //将ActivityStack与task进行绑定,并将task添加进mTaskHistory中
        final TaskRecord task = mTargetStack.createTaskRecord(
                mSupervisor.getNextTaskIdForUserLocked(mStartActivity.userId),
                mNewTaskInfo != null ? mNewTaskInfo : mStartActivity.info,
                mNewTaskIntent != null ? mNewTaskIntent : mIntent, mVoiceSession,
                mVoiceInteractor, !mLaunchTaskBehind /* toTop */, mStartActivity, mSourceRecord,
                mOptions);
        //绑定TaskRecord与ActivityRecord,并将ActivityRecord添加到TaskRecord的mActivities中
        addOrReparentStartingActivity(task, "setTaskFromReuseOrCreateNewTask - mReuseTask");
        updateBounds(mStartActivity.getTask(), mLaunchParams.mBounds);

    } else {
        addOrReparentStartingActivity(mReuseTask, "setTaskFromReuseOrCreateNewTask");
    }

    if (taskToAffiliate != null) {
        mStartActivity.setTaskToAffiliateWith(taskToAffiliate);
    }

    if (mService.getLockTaskController().isLockTaskModeViolation(mStartActivity.getTask())) {
        return START_RETURN_LOCK_TASK_MODE_VIOLATION;
    }

    if (mDoResume) {//成立
        //该方法用于设置ActivityStack,TaskRecord的位置;
        //将当前的ActivityStack放到ActivityDisplay.mStacks的首位;
        //将当前的ActivityStack设为mFocusedStack;
        //将当前的TaskRecord放到ActivityStack.mTaskHistory的首位;
        mTargetStack.moveToFront("reuseOrNewTask");
    }
    return START_SUCCESS;
}

点评:TaskRecord创建好了,相关的绑定操作也结束了,接下来继续看startActivityUnchecked()方法:

private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
        IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
        int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
        ActivityRecord[] outActivity) {
    ............
    ............
    //权限控制
    mService.grantUriPermissionFromIntentLocked(mCallingUid, mStartActivity.packageName,
            mIntent, mStartActivity.getUriPermissionsLocked(), mStartActivity.userId);
    mService.grantEphemeralAccessLocked(mStartActivity.userId, mIntent,
            mStartActivity.appInfo.uid, UserHandle.getAppId(mCallingUid));
    if (newTask) {
        EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, mStartActivity.userId,
                mStartActivity.getTask().taskId);
    }
    ActivityStack.logStartActivity(
            EventLogTags.AM_CREATE_ACTIVITY, mStartActivity, mStartActivity.getTask());
    mTargetStack.mLastPausedActivity = null;

    mSupervisor.sendPowerHintForLaunchStartIfNeeded(false /* forceSend */, mStartActivity);

    //调用mTargetStack.startActivityLocked,其中topFocused为Launcher,newTask为true
    mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
            mOptions);
    if (mDoResume) {//成立
        final ActivityRecord topTaskActivity =
                mStartActivity.getTask().topRunningActivityLocked();
        if (!mTargetStack.isFocusable()
                || (topTaskActivity != null && topTaskActivity.mTaskOverlay
                && mStartActivity != topTaskActivity)) {//不成立
           
            mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
            mService.mWindowManager.executeAppTransition();
        } else {
            if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
                mTargetStack.moveToFront("startActivityUnchecked");
            }
            //调用resumeFocusedStackTopActivityLocked()
            mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
                    mOptions);
        }
    } else if (mStartActivity != null) {
        mSupervisor.mRecentTasks.add(mStartActivity.getTask());
    }
    mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);

    mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(), preferredWindowingMode,
            preferredLaunchDisplayId, mTargetStack);

    return START_SUCCESS;
}

点评:调用mSupervisor.resumeFocusedStackTopActivityLocked()方法,继续执行;

boolean resumeFocusedStackTopActivityLocked(
        ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {

    if (!readyToResume()) {
        return false;
    }

    if (targetStack != null && isFocusedStack(targetStack)) {//满足
        //target为mStartActivity
        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)) {
        mFocusedStack.executeAppTransition(targetOptions);
    }

    return false;
}

调用:targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);

boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
    if (mStackSupervisor.inResumeTopActivity) {
        // Don't even start recursing.
        return false;
    }

    boolean result = false;
    try {
        // Protect against recursion.
        mStackSupervisor.inResumeTopActivity = true;
        //调用resumeTopActivityInnerLocked(),prev就是mStartActivity
        result = resumeTopActivityInnerLocked(prev, options);

        final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
        if (next == null || !next.canTurnScreenOn()) {
            checkReadyForSleep();
        }
    } finally {
        mStackSupervisor.inResumeTopActivity = false;
    }

    return result;
}

接着看:resumeTopActivityInnerLocked(prev, options);

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    if (!mService.mBooting && !mService.mBooted) {
        // Not ready yet!
        return false;
    }

    //取出第一个非finishing状态的activity,本例中即Settings
    final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);

    final boolean hasRunningActivity = next != null;//hasRunningActivity为true

    // TODO: Maybe this entire condition can get removed?
    if (hasRunningActivity && !isAttached()) {
        return false;
    }

    mStackSupervisor.cancelInitializingActivities();

    //记录并重置userLeaving,本例为true
    boolean userLeaving = mStackSupervisor.mUserLeaving;
    mStackSupervisor.mUserLeaving = false;

    if (!hasRunningActivity) {//不成立
        return resumeTopActivityInNextFocusableStack(prev, options, "noMoreActivities");
    }

    //不延迟
    next.delayedResume = false;

    /*如果前端显示的Activity就是当前要启动的Activity,则直接返回。
    此时前端显示的mResumedActivity仍然是Launcher,且处于Resume状态,要启动的next是Settings*/
    if (mResumedActivity == next && next.isState(RESUMED)
            && mStackSupervisor.allResumedActivitiesComplete()) {//不成立
        executeAppTransition(options);
        if (DEBUG_STATES) Slog.d(TAG_STATES,
                "resumeTopActivityLocked: Top activity resumed " + next);
        if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
        return false;
    }

    ............
    .............

    mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);

    boolean lastResumedCanPip = false;
    ActivityRecord lastResumed = null;
    final ActivityStack lastFocusedStack = mStackSupervisor.getLastStack();
    if (lastFocusedStack != null && lastFocusedStack != this) {//不成立
        lastResumed = lastFocusedStack.mResumedActivity;
        if (userLeaving && inMultiWindowMode() && lastFocusedStack.shouldBeVisible(next)) {
            userLeaving = false;
        }
        lastResumedCanPip = lastResumed != null && lastResumed.checkEnterPictureInPictureState(
                "resumeTopActivity", userLeaving /* beforeStopping */);
    }
    final boolean resumeWhilePausing = (next.info.flags & FLAG_RESUME_WHILE_PAUSING) != 0
            && !lastResumedCanPip;//resumeWhilePausing为false

    boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);
    /*启动目标Activity前,需要首先暂停当前显示的Activity。本例中,当前显示的仍然为Launcher*/
    if (mResumedActivity != null) {
        //首先暂停Launcher,这是我们遇到的第一个生命周期,next为Settings
        pausing |= startPausingLocked(userLeaving, false, next, false);
    }
    .........
    .........
    .........
}

点评:启动Settings之前,需要先暂停Launcher,先看下startPausingLocked()函数;

final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
        ActivityRecord resuming, boolean pauseImmediately) {
    //本例的mPausingActivity 暂时为null,此时还没确定需要暂停的Activity
    if (mPausingActivity != null) {//不成立
        if (!shouldSleepActivities()) {
            completePauseLocked(false, resuming);
        }
    }

    //本例中的prev是Launcher的ActivityRecord
    ActivityRecord prev = mResumedActivity;

    if (prev == null) {//不成立
        if (resuming == null) {
            mStackSupervisor.resumeFocusedStackTopActivityLocked();
        }
        return false;
    }

    //resuming是Settings
    if (prev == resuming) {//不成立
        return false;
    }

    //设置当前要暂停的Activity为Launcher
    mPausingActivity = prev;
    //设置上次暂停的Activity为Launcher
    mLastPausedActivity = prev;
    mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
            || (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null;
    //更改Launcher状态为正在暂停
    prev.setState(PAUSING, "startPausingLocked");
    prev.getTask().touchActiveTime();
    clearLaunchTime(prev);

    mStackSupervisor.getLaunchTimeTracker().stopFullyDrawnTraceIfNeeded(getWindowingMode());

    mService.updateCpuStats();

    //prev.app就是ProcessRecord,本例中表示Launcher的进程;
    //prev.app.thread即IApplicationThread,可以访问Launcher主线程
    if (prev.app != null && prev.app.thread != null) {//条件满足
        try {
            mService.updateUsageStats(prev, false);

            //下面的代码,就是暂停Launcher,这是AMS与ActivityThread交互的内容,暂时不讨论
            //prev.appToken为IApplicationToken.Stub,prev.finishing为false,userLeaving为true,异步执行
            mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
                    PauseActivityItem.obtain(prev.finishing, userLeaving,
                            prev.configChangeFlags, pauseImmediately));
        } catch (Exception e) {
            mPausingActivity = null;
            mLastPausedActivity = null;
            mLastNoHistoryActivity = null;
        }
    } else {
        mPausingActivity = null;
        mLastPausedActivity = null;
        mLastNoHistoryActivity = null;
    }

    /*非休眠和关机状态时,在Activity启动前需要保持设备处于唤醒(awake)状态*/
    if (!uiSleeping && !mService.isSleepingOrShuttingDownLocked()) {
        mStackSupervisor.acquireLaunchWakelock();
    }

    //mPausingActivity为Launcher
    if (mPausingActivity != null) {//成立
        if (!uiSleeping) {//成立
            //在新Activity启动前,暂停key dispatch事件
            prev.pauseKeyDispatchingLocked();
        } else if (DEBUG_PAUSE) {
             Slog.v(TAG_PAUSE, "Key dispatch not paused for screen off");
        }

        if (pauseImmediately) {//pauseImmediately为false
            completePauseLocked(false, resuming);
            return false;

        } else {
            //暂停一个Activity也需要指定超时处理,防止无响应,在本例中执行以下代码后返回
            schedulePauseTimeout(prev);
            return true;
        }

    } else {
        if (resuming == null) {
            //如果Pause操作失败,只需要启动栈顶Activity
            mStackSupervisor.resumeFocusedStackTopActivityLocked();
        }
        return false;
    }
}

点评:①首先是AMS与ActivityThread进行交互,暂停Launcher,具体流程后面会详细分析;

当Launcher调用了onPause()之后,会调用AMS的activityPaused()方法,进行下一步操作;

等会我们就要分析这个AMS的activityPaused()方法,AMS.activityPaused()最终会调用stack.activityPausedLocked()方法;

②暂停一个Activity需要指定超时处理,防止无响应,也就是调用schedulePauseTimeout(prev)方法,schedulePauseTimeout(prev)最终也会调用activityPausedLocked();

所以我们来看下activityPausedLocked():

final void activityPausedLocked(IBinder token, boolean timeout) {
    //此时的r为Launcher
    final ActivityRecord r = isInStackLocked(token);
    if (r != null) {
        //pause操作已经处理,移除之前添加的超时信息
        mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
        if (mPausingActivity == r) {//成立
            mService.mWindowManager.deferSurfaceLayout();
            try {
                //执行这一步
                completePauseLocked(true /* resumeNext */, null /* resumingActivity */);
            } finally {
                mService.mWindowManager.continueSurfaceLayout();
            }
            return;
        } else {
            EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
                    r.userId, System.identityHashCode(r), r.shortComponentName,
                    mPausingActivity != null
                        ? mPausingActivity.shortComponentName : "(none)");
            if (r.isState(PAUSING)) {
                if (r.finishing) {
                    finishCurrentActivityLocked(r, FINISH_AFTER_VISIBLE, false,
                            "activityPausedLocked");
                }
            }
        }
    }
    mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
}

执行completePauseLocked();

private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {
    ActivityRecord prev = mPausingActivity;

    //本例的prev为launcher
    if (prev != null) {
        prev.setWillCloseOrEnterPip(false);
        final boolean wasStopping = prev.isState(STOPPING);
        //切换Launcher的状态为PAUSED
        prev.setState(PAUSED, "completePausedLocked");
        //如果被暂停的Launcher处于finishing状态,则destroy
        if (prev.finishing) {//不成立
            prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false,
                    "completedPausedLocked");
        } else if (prev.app != null) {//成立
            //等待新启动Activity可见
            if (mStackSupervisor.mActivitiesWaitingForVisibleActivity.remove(prev)) {
                if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG_PAUSE,
                        "Complete pause, no longer waiting: " + prev);
            }
            if (prev.deferRelaunchUntilPaused) {
                prev.relaunchActivityLocked(false /* andResume */,
                        prev.preserveWindowOnDeferredRelaunch);
            } else if (wasStopping) {
                prev.setState(STOPPING, "completePausedLocked");
            } else if (!prev.visible || shouldSleepOrShutDownActivities()) {                prev.setDeferHidingClient(false);
                //加入待stop列表,等着被stop
                addToStopping(prev, true /* scheduleIdle */, false /* idleDelayed */);
            }
        } else {
            prev = null;
        }
        if (prev != null) {
            prev.stopFreezingScreenLocked(true /*force*/);
        }
        //已经处理Pause操作,重置mPausingActivity
        mPausingActivity = null;
    }

    //非休眠或者准备关机状态时,再次调用resumeFocusedStackTopActivityLocked
    if (resumeNext) {//成立
        final ActivityStack topStack = mStackSupervisor.getFocusedStack();
        if (!topStack.shouldSleepOrShutDownActivities()) {
            if (mService.mAppsLockOps != null) {

                ActivityRecord next = topStack.topRunningActivityLocked();
                if(DEBUG_APPLICATION_LOCK) {
                    Slog.v(TAG, "ApplicationLock in resumeNext: next = " + next.toString());
                }

                int result = 0;
                if (next != null) {
                    result = mService.mAppsLockOps.isPackageNeedLocked(next.packageName,
                            next.info.name, mService.isSleepingLocked(), next.userId);
                }

                if ((result != GomeApplicationsLockOps.APPLICATION_LOCK_DO_NOT_NEED_LOCK)) {
                    mService.showAccessInActivityThread(next, next.packageName,
                            next.userId);
                } else {
                    mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);
                }

            } else {
                //调用resumeFocusedStackTopActivityLocked();
                //topStack是Settings的ActivityStack,prev为Launcher
                mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);
            }
        } else {
            checkReadyForSleep();
            ActivityRecord top = topStack.topRunningActivityLocked();
            if (top == null || (prev != null && top != prev)) {
                mStackSupervisor.resumeFocusedStackTopActivityLocked();
            }
        }
    }

    //恢复接收WindowManagerService的Key Dispatch事件
    if (prev != null) {
        ............
        ............
    }

    if (mStackSupervisor.mAppVisibilitiesChangedSinceLastPause
            || getDisplay().hasPinnedStack()) {
        mService.mTaskChangeNotificationController.notifyTaskStackChanged();
        mStackSupervisor.mAppVisibilitiesChangedSinceLastPause = false;
    }

    mStackSupervisor.ensureActivitiesVisibleLocked(resuming, 0, !PRESERVE_WINDOWS);
}

点评:上述代码有2个重要逻辑:

① addToStopping();

将Laucher加入到待stop列表,等着被stop,看下它的代码:

void addToStopping(ActivityRecord r, boolean scheduleIdle, boolean idleDelayed) {
    if (!mStackSupervisor.mStoppingActivities.contains(r)) {
        //将Launcher添加进mStoppingActivities中,再Settings的onResume方法调用结束后,会调用Launcher的onStop方法
        mStackSupervisor.mStoppingActivities.add(r);
    }

    //stop列表中Activity数大于3时,发送并处理IDLE_NOW_MSG消息
    boolean forceIdle = mStackSupervisor.mStoppingActivities.size() > MAX_STOPPING_TO_FORCE
            || (r.frontOfTask && mTaskHistory.size() <= 1);
    if (scheduleIdle || forceIdle) {
        if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Scheduling idle now: forceIdle="
                + forceIdle + "immediate=" + !idleDelayed);
        if (!idleDelayed) {
            //发送IDLE_NOW_MSG消息,收到消息后调用activityIdleInternal()
            mStackSupervisor.scheduleIdleLocked();
        } else {
            mStackSupervisor.scheduleIdleTimeoutLocked(r);
        }
    } else {
        checkReadyForSleep();
    }
}

将Launcher添加进mStoppingActivities中后,调用mStackSupervisor.scheduleIdleLocked()发送IDLE_NOW_MSG消息,收到消息后调用activityIdleInternal(),关于activityIdleInternal()函数后面能看到,这里先不分析;

②非休眠或者准备关机状态时,再次调用mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null),最终会调用resumeTopActivityInnerLocked()方法;

继续回到resumeTopActivityInnerLocked():

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
    ............
    ............
    boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);
    /*启动目标Activity前,需要首先暂停当前显示的Activity。本例中,当前显示的仍然为Launcher*/
    if (mResumedActivity != null) {
        //首先暂停Launcher,这是我们遇到的第一个生命周期
        pausing |= startPausingLocked(userLeaving, false, next, false);
    }

    /// M: onBeforeActivitySwitch @{
    mService.mAmsExt.onBeforeActivitySwitch(mService.mLastResumedActivity, next, pausing,
            next.getActivityType());
    /// M: onBeforeActivitySwitch @}

    if (pausing && !resumeWhilePausing) {//不成立
        ............
............
        return true;
    } else if (mResumedActivity == next && next.isState(RESUMED)
            && mStackSupervisor.allResumedActivitiesComplete()) {//不成立
      ............
        return true;
    }

    ............
    ............

    //perv是Settings,next也是Settings
    if (prev != null && prev != next) {//不成立
        if (!mStackSupervisor.mActivitiesWaitingForVisibleActivity.contains(prev)
                && next != null && !next.nowVisible) {
            mStackSupervisor.mActivitiesWaitingForVisibleActivity.add(prev);
        } else {
            //prev处于finish状态时,需要立刻使其不可见,从而使新Activity立刻可见。prev处于非finish状态时需要根据新Activity是否占满全屏决定prev是否可见
            if (prev.finishing) {
                prev.setVisibility(false);
            } else {
            }
        }
    }

    //确定应用程序非stop状态
    try {
        AppGlobals.getPackageManager().setPackageStoppedState(
                next.packageName, false, next.userId); /* TODO: Verify if correct userid */
    } catch (RemoteException e1) {
    } catch (IllegalArgumentException e) {
        Slog.w(TAG, "Failed trying to unstop package "
                + next.packageName + ": " + e);
    }
            ............
    boolean anim = true;
    if (prev != null) {
        if (prev.finishing) {//不满足该分支
           ............
        } else {//满足该分支
            ............
        }
    } else {
        //准备切换动画
       ............
    }

    if (anim) {
        next.applyOptionsLocked();
    } else {
        next.clearOptionsLocked();//Options存储切换动画的信息,不需要动画便清空
    }

    mStackSupervisor.mNoAnimActivities.clear();

    ActivityStack lastStack = mStackSupervisor.getLastStack();
    //next.app为ProcessRecord,此时还未创建应用程序进程,因此为null
    if (next.app != null && next.app.thread != null) {//不满足
      .........
    } else {//满足
        // Whoops, need to restart this activity!
        if (!next.hasBeenLaunched) {//该Activity是否已经启动过,此时为false
            next.hasBeenLaunched = true;
        } else {//如果Activity已启动,则直接执行restart
            if (SHOW_APP_STARTING_PREVIEW) {
                //显示一个窗口前,先显示一个过渡窗口
                next.showStartingWindow(null /* prev */, false /* newTask */,
                        false /* taskSwich */);
            }
        }
        //执行到这里,终于要开始Settings的神奇启动之旅了!
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
    }

    if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
    return true;
}

点评:走到了mStackSupervisor.startSpecificActivityLocked(next, true, true),终于要开始Settings的神奇启动之旅了:

void startSpecificActivityLocked(ActivityRecord r,
        boolean andResume, boolean checkConfig) {
    //获取即将启动的Activity的所在的应用程序进程,ProcessRecord将记录Settings的进程信息,包括UID、进程名、UI主线程等
    //第一次启动Activity,此时其应用程序进程还没有创建,因此app为null
    ProcessRecord app = mService.getProcessRecordLocked(r.processName, r.info.applicationInfo.uid, true);

    getLaunchTimeTracker().setLaunchTime(r);

    //判断要启动的Acitivty所在的应用程序进程是否已经运行
    //startSpecificActivityLocked()方法会走两次,第一次启动的时候,不满足下面的条件,第二次启动的时候满足
    if (app != null && app.thread != null) {
        try {
            //应用进程已经存在,则直接启动Activity
            if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                    || !"android".equals(r.info.packageName)) {
                app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
                        mService.mProcessStats);
            }
            //真正启动Settings的逻辑在这里
            realStartActivityLocked(r, app, andResume, checkConfig);
            return;
        } catch (RemoteException e) {
            Slog.w(TAG, "Exception when starting activity "
                    + r.intent.getComponent().flattenToShortString(), e);
        }
    }

    //否则,启动应用程序进程,最终还是要执行realStartActivityLocked
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0, "activity", r.intent.getComponent(), false, false, true);
}

上面的代码用于获取Settings的进程,Settings此时还没有进程,所以得给它创建一个进程mService.startProcessLocked(),由于创建进程的逻辑不是我们分析的关键点,所以就不详细解释了,看mService.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 (!isolated) {
        //对于非isolated的app,需要从mProcessNames中查询是否已经存在其进程信息
        app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
        checkTime(startTime, "startProcess: after getProcessRecord");

        if ((intentFlags & Intent.FLAG_FROM_BACKGROUND) != 0) {
            if (mAppErrors.isBadProcessLocked(info)) {
                return null;
            }
        } else {
            mAppErrors.resetProcessCrashTimeLocked(info);
            if (mAppErrors.isBadProcessLocked(info)) {
                EventLog.writeEvent(EventLogTags.AM_PROC_GOOD,
                        UserHandle.getUserId(info.uid), info.uid,
                        info.processName);
                mAppErrors.clearBadProcessLocked(info);
                if (app != null) {
                    app.bad = false;
                }
            }
        }
    } else {
     //对于isolated的app,不能复用已经存在的进程
     app = null;
    }

    /*在本例中,processName=com.android.settings,app=null,knownToBeDead=true,thread=null,pid=-1*/
    if (app != null && app.pid > 0) {//复用已有的进程
        if ((!knownToBeDead && !app.killed) || app.thread == null) {
            app.addPackage(info.packageName, info.versionCode, mProcessStats);
            checkTime(startTime, "startProcess: done, added package to proc");
            return app;
        }

        checkTime(startTime, "startProcess: bad proc running, killing");
        killProcessGroup(app.uid, app.pid);
        handleAppDiedLocked(app, true, true);
        checkTime(startTime, "startProcess: done killing old proc");
    }

    //hostingName表示运行于该进程的组件类型,本例中为Activity
    String hostingNameStr = hostingName != null ? hostingName.flattenToShortString() : null;

    if (app == null) {
        checkTime(startTime, "startProcess: creating new process record");
     //创建一个新的ProcessRecord
        app = newProcessRecordLocked(info, processName, isolated, isolatedUid);
        if (app == null) {
            return null;
        }
        app.crashHandler = crashHandler;
        app.isolatedEntryPoint = entryPoint;
        app.isolatedEntryPointArgs = entryPointArgs;
        checkTime(startTime, "startProcess: done creating new process record");
    } else {
        app.addPackage(info.packageName, info.versionCode, mProcessStats);
        checkTime(startTime, "startProcess: added package to existing proc");
    }

    /*mProcessesReady是在ActivityManagerService的systemReady执行完程序升级后,赋值为true的。 该值表明此时系统进入可以真正启动应用程序的阶段'
 如果还没有进入此状态,需要先将启动的应用进程加入mProcessesOnHold列表中等待*/
    if (!mProcessesReady
            && !isAllowedWhileBooting(info)
            && !allowWhileBooting) {
        if (!mProcessesOnHold.contains(app)) {
            mProcessesOnHold.add(app);
        }
        checkTime(startTime, "startProcess: returning with proc on hold");
        return app;
    }

    checkTime(startTime, "startProcess: stepping in to startProcess");
    //调用重载方法startProcessLocked(ProcessRecord app,……)
    final boolean success = startProcessLocked(app, hostingType, hostingNameStr, abiOverride);
    checkTime(startTime, "startProcess: done starting proc!");
    return success ? app : null;
}

继续调用startProcessLocked():

private final boolean startProcessLocked(ProcessRecord app, String hostingType,
        String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) {
    if (app.pendingStart) {
        return true;
    }
    long startTime = SystemClock.elapsedRealtime();
    /*如果已经指定了PID且非当前进程的PID,需要从已有记录中删除,本例app.pid未分配,值为0;MY_PID是system_server的进程ID*/
    if (app.pid > 0 && app.pid != MY_PID) {
        ............
    }

    //从mProcessesOnHold列表中删除等待的ProcessRecord
    mProcessesOnHold.remove(app);

    checkTime(startTime, "startProcess: starting to update cpu stats");
    updateCpuStats();
    checkTime(startTime, "startProcess: done updating cpu stats");

    try {
        ............
        if (!app.isolated) {
            int[] permGids = null;
            try {
                checkTime(startTime, "startProcess: getting gids from package manager");
                final IPackageManager pm = AppGlobals.getPackageManager();
                // 通过PackageManagerService获取应用程序组ID
                permGids = pm.getPackageGids(app.info.packageName,
                        MATCH_DEBUG_TRIAGED_MISSING, app.userId);
                StorageManagerInternal storageManagerInternal = LocalServices.getService(
                        StorageManagerInternal.class);
                mountExternal = storageManagerInternal.getExternalStorageMountMode(uid,
                        app.info.packageName);
            } catch (RemoteException e) {
                throw e.rethrowAsRuntimeException();
            }
            ............

        //调用startProcessLocked方法
        return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids,
                runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith,
                startTime);
    } catch (RuntimeException e) {
        forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), false,
                false, true, false, false, UserHandle.getUserId(app.userId), "start failure");
        return false;
    }
}

继续调用startProcessLocked():

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 {
                synchronized (ActivityManagerService.this) {
                   ............
                }
                //startProcess--->Process.start()方法fork出一个子进程
                final ProcessStartResult startResult = startProcess(app.hostingType, entryPoint,
                        app, app.startUid, gids, runtimeFlags, mountExternal, app.seInfo,
                        requiredAbi, instructionSet, invokeWith, app.startTime);
                synchronized (ActivityManagerService.this) {
                    //打印log,发送超时通知等
                    handleProcessStartedLocked(app, startResult, startSeq);
                }
            } catch (RuntimeException e) {
                ............
            }
        });
        return true;
    } else {
        ............
        return app.pid > 0;
    }
}

调用startProcess()方法fork出一个子进程:

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 {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " +
                app.processName);
        checkTime(startTime, "startProcess: asking zygote to start proc");
        final ProcessStartResult startResult;
        if (hostingType.equals("webview_service")) {
            startResult = startWebView(entryPoint,
                    app.processName, uid, uid, gids, runtimeFlags, mountExternal,
                    app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet,
                    app.info.dataDir, null,
                    new String[] {PROC_START_SEQ_IDENT + app.startSeq});
        } else {
         // 设置Zygote调试标记,会读取属性配置
         /*通过zygote启动一个新的进程。其本质仍然是fork出一个子进程,然后在子进程中
执行android.app.ActivityThread类的main方法,关于ActivityThread.main()属于IPC部分的,后面在分析*/
         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 {
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
    }
}

点评:当Settings进程被fork出来后,就会调用该进程中的ActivityThread.main()方法,在ActivityThread.main()中,会创建进程的ActivityThread以及ApplicationThread,并调用它的ActivityThread.attach(),在该方法中,会调用AMS.attachApplication()方法,由于这个过程属于AMS与ActivityThread交互部分,暂时不讨论,我们先分析AMS.attachApplication()方法:

public final void attachApplication(IApplicationThread thread, long startSeq) {
    synchronized (this) {
        int callingPid = Binder.getCallingPid();
        final int callingUid = Binder.getCallingUid();
        final long origId = Binder.clearCallingIdentity();
        //调用attachApplicationLocked(),thread就是Settings的ApplicationTread
        attachApplicationLocked(thread, callingPid, callingUid, startSeq);
        Binder.restoreCallingIdentity(origId);
    }
}

继续看attachApplicationLocked():

private final boolean attachApplicationLocked(IApplicationThread thread,
        int pid, int callingUid, long startSeq) {

    ProcessRecord app;
    long startTime = SystemClock.uptimeMillis();
    //传入的PID是Settings的PID,而MY_PID代表system_process
    if (pid != MY_PID && pid >= 0) {
        synchronized (mPidsSelfLocked) {
            //根据PID查找当前正在运行的应用程序对应的ProcessRecord
            app = mPidsSelfLocked.get(pid);
        }
    } else {
        app = null;
    }

    if (app == null && startSeq > 0) {//不成立
        ............
    }

    /*应用程序在执行attach方法之前,都会在ActivityManagerService中有对应的ProcessRecord,如果没有,说明出现问题,需要杀死该进程*/
    if (app == null) {//不成立
        ............
    }

    ............

    final String processName = app.processName;
    try {
        //通过AppDeathRecipient监控进程退出
        AppDeathRecipient adr = new AppDeathRecipient(
                app, pid, thread);
        thread.asBinder().linkToDeath(adr, 0);
        app.deathRecipient = adr;
    } catch (RemoteException e) {
        app.resetPackageList(mProcessStats);
        startProcessLocked(app, "link fail", processName);
        return false;
    }

    EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName);

    //将ApplicationThread与ProcessRecord绑定
    app.makeActive(thread, mProcessStats);
    //设置进程的OOM adj、线程组等信息
    app.curAdj = app.setAdj = app.verifiedAdj = ProcessList.INVALID_ADJ;

    ............

    //启动应用程序进程已完成,从消息队列中移除在调用attach方法之前设置的超时信息
    mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);

    boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
    //通过PackageManagerService获取该应用程序中定义的ContentProvider
    List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null;
    try {
        ...........
       
        if (app.isolatedEntryPoint != null) {
            thread.runIsolatedEntryPoint(app.isolatedEntryPoint, app.isolatedEntryPointArgs);
        } else if (app.instr != null) {//成立
            //关键点在这,调用ActivityThread的bindApplication方法
            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);
        } else {
            ............
        }
        ............
    } catch (Exception e) {
        ............
    }

    ............

    if (normalMode) {
        try {
         //执行完ActivityThread.bindApplication,接下来执行mStackSupervisor.attachApplicationLocked();
         //主要功能是加载Activity,并执行其生命周期的onCreate、onStart、onResume等方法,最终显示Activity。
         if (mStackSupervisor.attachApplicationLocked(app)) {
                didSomething = true;
            }
        } catch (Exception e) {
           ............
        }
    }

    // Find any services that should be running in this process...
    //执行因为等待进程创建而暂时挂起的Services
    if (!badApp) {
        ............
    }

    //发送因为等待进程创建而暂时挂起的广播
    if (!badApp && isPendingBroadcastProcessLocked(pid)) {
        ............
    }

    ............

    if (!didSomething) {
        //执行了以上启动组件的操作,需要调整OOM adj
        updateOomAdjLocked();
        checkTime(startTime, "attachApplicationLocked: after updateOomAdjLocked");
    }
    return true;
}

点评:上述代码有两块比较重要的内容,

①thread.bindApplication();

ActivityThread的bindApplication()方法,主要是在ActivityThread中初始化应用程序的Context,初始化Instrumentation,创建应用程序的Application,调用Application的onCreate方法等,后面会详细分析;

②mStackSupervisor.attachApplicationLocked(app);

主要功能是加载Activity,并执行其生命周期的onCreate、onStart、onResume等方法,最终显示Activity;

主要来分析mStackSupervisor.attachApplicationLocked(app):

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 {
                        //调用realStartActivityLocked()
                        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;
}

继续调用realStartActivityLocked():

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
        boolean andResume, boolean checkConfig) throws RemoteException {

    ............

    try {
        /*当Activity attach到Application,并且应用进程没有异常状态(crash,ANR)时,需要通过WindowManagerService冻结屏幕并设置Activity可见*/
        r.startFreezingScreenLocked(app, 0);

        // schedule launch ticks to collect information about slow apps.
        r.startLaunchTickingLocked();

        //在ActivityRecord中记录ProcessRecord,即Activity需要保存其运行进程的信息
        r.setProcess(app);

        ............

        final int applicationInfoUid =
                (r.info.applicationInfo != null) ? r.info.applicationInfo.uid : -1;
        if ((r.userId != app.userId) || (r.appInfo.uid != applicationInfoUid)) {
        }

        app.waitingToKill = null;
        r.launchCount++;
        r.lastLaunchTime = SystemClock.uptimeMillis();

        if (DEBUG_ALL) Slog.v(TAG, "Launching: " + r);

        //在ProcessRecord中记录ActivityRecord,一个进程可以运行多个Activity
        int idx = app.activities.indexOf(r);
        if (idx < 0) {
            app.activities.add(r);
        }
        
        //更新LRU
        mService.updateLruProcessLocked(app, true, null);
        mService.mHandler.post(mService::updateOomAdj);

        final LockTaskController lockTaskController = mService.getLockTaskController();
        if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE
                || task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV
                || (task.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED
                        && lockTaskController.getLockTaskModeState()
                                == LOCK_TASK_MODE_LOCKED)) {
            lockTaskController.startLockTaskMode(task, false, 0 /* blank UID */);
        }

        try {
            //此时已经创建应用程序主线程,这里不为null
            if (app.thread == null) {
                throw new RemoteException();
            }
            List<ResultInfo> results = null;
            List<ReferrerIntent> newIntents = null;
            if (andResume) {//本例为true
                results = r.results;
                newIntents = r.newIntents;
            }
            EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY, r.userId,
                    System.identityHashCode(r), task.taskId, r.shortComponentName);
                mService.mHomeProcess = task.mActivities.get(0).app;
            }

            ............

            // Create activity launch transaction.
            final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
                    r.appToken);
            //①先将LaunchActivityItem做为Callback
            clientTransaction.addaddCallback(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));

            // Set desired final state.
            final ActivityLifecycleItem lifecycleItem;
            if (andResume) {//andResume为true
                lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
            } else {
                lifecycleItem = PauseActivityItem.obtain();
            }
            //②再设置ResumeActivityItem
            clientTransaction.setLifecycleStateRequest(lifecycleItem);

            // Schedule transaction.
            //scheduleTransaction会一次调用LaunchActivityItem和ResumeActivityItem的execute()方法,
            //接下来调用Activity生命周期,主要包括 onCreate、 onStart 和 onResume
            mService.getLifecycleManager().scheduleTransaction(clientTransaction);

            ............

        } catch (RemoteException e) {
            ............
        }
    } finally {
        endDeferResume();
    }

    r.launchFailed = false;
    if (stack.updateLRUListLocked(r)) {
        Slog.w(TAG, "Activity " + r + " being launched, but already in LRU list");
    }

    if (andResume && readyToResume()) {//andResume为true
        //执行onResume后的处理,如设置ActivityRecord的state为RESUMED
        stack.minimalResumeActivityLocked(r);
    } else {
        if (DEBUG_STATES) Slog.v(TAG_STATES,
                "Moving to PAUSED: " + r + " (starting in paused state)");
        r.setState(PAUSED, "realStartActivityLocked");
    }

    if (isFocusedStack(stack)) {
        //系统升级时或第一次启动时需要运行Setup Wizard
        mService.getActivityStartController().startSetupActivity();
    }

    if (r.app != null) {
        mService.mServices.updateServiceConnectionActivitiesLocked(r.app);
    }

    return true;
}

上述代码中:

①LaunchActivityItem:

它对应着ActivityThread的handleLaunchActivity(),主要是调用Activity.attach()方法初始化Activity,后面会详细分析;

②ResumeActivityItem:

它对应着Activity的生命周期,主要包括 onCreate、onStart和onResume,后面会详细分析;

 

后面在分析ResumeActivityItem的时候,看到在ActivityThread.handleResumeActivity()中有这么一句代码:

Looper.myQueue().addIdleHandler(new Idler());

Activity在onResume后就进入了Idle状态,此时将向主线程的消息队列注册IdleHandler,它会调用AMS.activityIdle()方法;

因为这个代码跟Launcher的stop有关,我们来分析下它的流程:

public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
    final long origId = Binder.clearCallingIdentity();
    synchronized (this) {
        ActivityStack stack = ActivityRecord.getStackLocked(token);
        if (stack != null) {
            //调用mStackSupervisor.activityIdleInternalLocked()
            ActivityRecord r =
                    mStackSupervisor.activityIdleInternalLocked(token, false /* fromTimeout */,
                            false /* processPausingActivities */, config);
            if (stopProfiling) {
                if ((mProfileProc == r.app) && mProfilerInfo != null) {
                    clearProfilerLocked();
                }
            }
            /// M: DuraSpeed
            mAmsExt.onEndOfActivityIdle(mContext, r.intent);
        }
    }
    Binder.restoreCallingIdentity(origId);
}

继续看:

final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
        boolean processPausingActivities, Configuration config) {
    if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token);

    ArrayList<ActivityRecord> finishes = null;
    ArrayList<UserState> startingUsers = null;
    int NS = 0;
    int NF = 0;
    boolean booting = false;
    boolean activityRemoved = false;

    ActivityRecord r = ActivityRecord.forTokenLocked(token);
    if (r != null) {
        //从ActivityStack的消息队列中移除IDLE_TIMEOUT_MSG消息
        mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
        r.finishLaunchTickingLocked();
        if (fromTimeout) {//不成立
            reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
        }
 
       ............

    }

    ............

    // Atomically retrieve all of the other things to do.
    /*获取mStoppingActivities中存储的待停止的Activity,暂停阶段由completePauseLocked方法将源Activity存入该列表*/
    final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,
            true /* remove */, processPausingActivities);
    NS = stops != null ? stops.size() : 0;
    if ((NF = mFinishingActivities.size()) > 0) {
        finishes = new ArrayList<>(mFinishingActivities);
        mFinishingActivities.clear();
    }

    if (mStartingUsers.size() > 0) {
        startingUsers = new ArrayList<>(mStartingUsers);
        mStartingUsers.clear();
    }

    //启动目标Activity会导致停止其他Activity,包括源Activity
    for (int i = 0; i < NS; i++) {
        r = stops.get(i);
        final ActivityStack stack = r.getStack();
        if (stack != null) {
            if (r.finishing) {
                /*如果源Activity处于finishing状态,需要调用其onDestroy方法,
通常发生在源Activity在onPause方法中调用了finish方法*/
                stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false,
                        "activityIdleInternalLocked");
            } else {
                //否则直接调用源Activity的onStop方法
                stack.stopActivityLocked(r);
            }
        }
    }

    //启动目标Activity可能导致需要回收其他Activity
    for (int i = 0; i < NF; i++) {
        r = finishes.get(i);
        final ActivityStack stack = r.getStack();
        if (stack != null) {
            activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
        }
    }

    if (!booting) {//本例的booting为false
        // Complete user switch
        if (startingUsers != null) {
            for (int i = 0; i < startingUsers.size(); i++) {
                mService.mUserController.finishUserSwitch(startingUsers.get(i));
            }
        }
    }

    //回收应用程序进程,并更新OOM adj
    mService.trimApplications();
    //dump();
    //mWindowManager.dump();

    if (activityRemoved) {//本例为false
        resumeFocusedStackTopActivityLocked();
    }

    return r;
}

点评:在之前的completePauseLocked()方法中我们就将待停止的Launcher添加进了mStoppingActivities中,现在就要开始调用Launcher的stop()方法了;

继续看stack.stopActivityLocked(r):

final void stopActivityLocked(ActivityRecord r) {
   .............
    if (r.app != null && r.app.thread != null) {
        adjustFocusedActivityStack(r, "stopActivity");
        r.resumeKeyDispatchingLocked();
        try {
            r.stopped = false;
            if (DEBUG_STATES) Slog.v(TAG_STATES,
                    "Moving to STOPPING: " + r + " (stop requested)");
            //设置状态
            r.setState(STOPPING, "stopActivityLocked");
            if (DEBUG_VISIBILITY) Slog.v(TAG_VISIBILITY,
                    "Stopping visible=" + r.visible + " for " + r);
            if (!r.visible) {
                //设置可见性
                r.setVisible(false);
            }
            EventLogTags.writeAmStopActivity(
                    r.userId, System.identityHashCode(r), r.shortComponentName);
            //使用StopActivityItem,完成了Launcher的onStop()方法调用
            mService.getLifecycleManager().scheduleTransaction(r.app.thread, r.appToken,
                    StopActivityItem.obtain(r.visible, r.configChangeFlags));
            if (shouldSleepOrShutDownActivities()) {
                r.setSleeping(true);
            }
            Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
            mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
        } catch (Exception e) {
           ............
        }
    }
}

点评:修改Launcher的状态,并且使用StopActivityItem,完成了Launcher的onStop()方法调用,后面会具体分析;

 

分析到了这里,根Activity的启动流程基本结束了,现在,Settings已经显示出来,而Launcher正在stop状态;

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

renshuguo123723

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值