Android进阶——Android四大组件启动机制之Activity启动过程

前言

Activity启动过程涉及到的比较多的知识点有Binder的跨进程通讯,建议先看完Binder的跨进程通讯再来阅读本篇文章,在文章阅读开始,我们先要理解Activity启动模型,再者去理解有关Activity启动的基本概念,梳理Activity启动流程,这样在看源码的时候可以根据这条流程往下走。文章的主要目的是弄清楚基本概念,对启动流程有个大概的认识即可。

启动模型

借用Gityuan博客的一张图,很形象的概括启动过程的整个过程,具体如图所示

这里写图片描述

基本概念

一、从大体角度

  • Instrumentation:负责监控系统与应用之间的交互
  • ActivityThread:描述应用程序进程

二、从细节角度

  • ActivityStackSupervisor(ASS):负责管理多个ActivityStack
  • ActivityStack(AS):栈式管理结构,负责管理栈内的TaskRecord,栈顶的TaskRecord表示当前可见的任务
  • TaskRecord(TR):栈式管理结构,负责管理栈内的ActivityRecord,栈顶的ActivityRecord表示当前可见的界面
  • ActivityRecord(AR):负责维护对应的Activity组件的运行状态以及信息
  • ProcessRecord(PR):记录着属于一个进程的所有ActivityRecord,ActivityRecord可能跟运行在TaskRecord中的ActivityRecord属于同一个

这里会用一张比较直观的图来解释它们的关系

这里写图片描述

三、从跨进程角度

启动过程中会涉及到Binder通讯,需要理解这几个基本概念

  • ActivityManagerService(AMS):负责系统中四大组件的启动、切换、调度及应用进程的管理和调度等工作
  • ActivityManagerNative(AMN):AMS的Binder本地对象
  • ActivityManagerProxy(AMP):AMS的Binder代理对象
  • ApplicationThread(AT):接收AMS的指令并与ActivityThread通讯,是ActivityThread与AMS连接的桥梁
  • ApplicationThreadNative(ATN):AT的Binder本地对象
  • ApplicationThreadProxy(ATP):AT的Binder代理对象

概念详解

一、ProcessRecord

属性 描述
BatteryStats 电量统计的接口
ApplicationInfo 系统进程的ApplicationInfo是从android包中解析出来的数据,应用程序的ApplicationInfo是从AndroidManifest.xml中解析出来的数据
Process Name 进程名称
UID 进程的UID。系统进程的UID是1000(Process.SYSTEM_UID),应用进程的UID是从10000(Process.FIRST_APPLICATION_UID)开始分配的
maxAdj, curAdj, setAdj 各种不同的OOM Adjustment值
lastPss, lastPssTime 物理内存(PSS)相关,进程中有对象创建或销毁时,PSS相关的属性会被更新
activities, services, receivers 进程中的Android组件,随着进程的运行,这些信息都可能需要更新
pkgList 进程中运行的包
thread 该属性是IApplicationThread类型的对象,当ProcessRecord绑定到一个实际进程的时候,thread会被赋值

二、ActivityRecord

属性 描述
ActivityInfo 从标签中解析出来的信息,包含launchMode,permission,taskAffinity等
mActivityType Activity的类型有三种:APPLICATION_ACTIVITY_TYPE(应用)、HOME_ACTIVITY_TYPE(桌面)、RECENTS_ACTIVITY_TYPE(最近使用)
appToken 当前ActivityRecord的标识
packageName 当前所属的包名,这是由静态定义的
processName 当前所属的进程名,大部分情况都是由静态定义的,但也有例外
taskAffinity 相同taskAffinity的Activity会被分配到同一个任务栈中
intent 启动当前Activity的Intent
launchedFromUid 启动当前Activity的UID,即发起者的UID
launchedFromPackage 启动当前Activity的包名,即发起者的包名
resultTo resultTo表示上一个启动它的ActivityRecord,当需要启动另一个ActivityRecord,会把自己作为resultTo,传递给下一个ActivityRecord
state ActivityRecord所处的状态,初始值是ActivityState.INITIALIZING
app ActivityRecord的宿主进程
task ActivityRecord的宿主任务
inHistory 标识当前的ActivityRecord是否已经置入任务栈中
frontOfTask 标识当前的ActivityRecord是否处于TaskRecord的栈顶
newIntents Intent数组,用于暂存还没有调度到应用进程Activity的Intent

三、TaskRecord

属性 描述
taskid TaskRecord的唯一标识
taskType 任务栈的类型,等同于ActivityRecord的类型,是由任务栈的第一个ActivityRecord决定的
intent 在当前任务栈中启动的第一个Activity的Intent将会被记录下来,后续如果有相同的Intent时,会与已有任务栈的Intent进行匹配,如果匹配上了,就不需要再新建一个TaskRecord了
realActivity, origActivity 启动任务栈的Activity,这两个属性是用包名(CompentName)表示的,real和orig是为了区分Activity有无别名的情况,如果AndroidManifest.xml中定义的Activity是一个alias,则此处real表示Activity的别名,orig表示真实的Activity
affinity TaskRecord把Activity的affinity记录下来,后续启动Activity时,会从已有的任务栈中匹配affinity,如果匹配上了,则不需要新建TaskRecord
rootAffinity 记录任务栈中最底部Activity的affinity,一经设定后就不再改变
mActivities TaskRecord是一个栈结构,栈的元素是ActivityRecord,其内部实现是一个数组mActivities
stack 当前TaskRecord所在的ActivityStack

四、ActivityStack

属性 描述
stackId 每一个ActivityStack都有一个编号,从0开始递增。编号为0,表示桌面所在的ActivityStack(HomeStack)
mTaskHistory TaskRecord数组,ActivityStack栈就是通过这个数组实现的
mPausingActivity 当前处于Pausing状态的Activity
mResumedActivity 当前处于Resumed状态的Activity
mStacks 当ActivityStack执行一次设备绑定操作时,就会将mStacks这个属性赋值成ActivityDisplay.mStacks

五、ActivityStackSupervisor

属性 描述
mHomeStack 主屏(桌面)所在ActivityStack
mFocusedStack 表示焦点ActivityStack,它能够获取用户输入
mLastFocusedStack 上一个焦点ActivityStack
mActivityDisplays 表示当前的显示设备,ActivityDisplay中绑定了若干ActivityStack

启动流程

这里使用一张图来介绍启动流程最适合不过了

这里写图片描述

简单的总结整个流程

  1. 构建启动的ActivityRecord
  2. 寻找当前宿主的TaskRecord
  3. 将TaskRecord挪到ActivityStack的栈顶位置
  4. 将ActivityRecord插入到TaskRecord栈顶位置
  5. 进行常规检查,权限检查,启动参数修正
  6. 将当前正在显示的Activity迁移到Pausing状态
  7. 尝试将栈顶的ActivityRecord迁移到Resumed状态
  8. 真正启动Activity,走生命周期

源码分析

由于前面的知识点已经讲得非常多了,在看源码的过程中对基本概念不会有太多解释,各位可以时不时的翻回去对照下各个类的作用

1、Activity.startActivity

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

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

startActivityForResult参数-1表示不关心启动后结果的返回

2、Activity.startActivityForResult

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

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

mMainThread.getApplicationThread():数据类型为ApplicationThread的Binder本地对象
mToken: 数据类型为IBinder,为Binder代理对象,但它指向AMS的AR的Binder本地对象

3、Instrumentation.execStartActivity

public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) {

    IApplicationThread whoThread = (IApplicationThread) contextThread;
    ...

    try {
        ...
        int result = ActivityManagerNative.getDefault()
            .startActivity(whoThread, who.getBasePackageName(), intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()),
                    token, target != null ? target.mEmbeddedID : null,
                    requestCode, 0, null, options);
        ...
    } catch (RemoteException e) {
        throw new RuntimeException("Failure from system", e);
    }
    return null;
}

ActivityManagerNative.getDefault():获取AMS的代理对象AMP,从而来通知启动Activity组件

4、AMP.startActivity

class ActivityManagerProxy implements IActivityManager {
    ...
    public int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
        Parcel data = Parcel.obtain();
        Parcel reply = Parcel.obtain();
        data.writeInterfaceToken(IActivityManager.descriptor);
        data.writeStrongBinder(caller != null ? caller.asBinder() : null);
        data.writeString(callingPackage);
        intent.writeToParcel(data, 0);
        data.writeString(resolvedType);
        data.writeStrongBinder(resultTo);
        data.writeString(resultWho);
        data.writeInt(requestCode);
        data.writeInt(startFlags);
        if (profilerInfo != null) {
            data.writeInt(1);
            profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
        } else {
            data.writeInt(0);
        }
        if (options != null) {
            data.writeInt(1);
            options.writeToParcel(data, 0);
        } else {
            data.writeInt(0);
        }
        mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
        reply.readException();
        int result = reply.readInt();
        reply.recycle();
        data.recycle();
        return result;
    }
    ...
}

由Binder中AIDL知识可知,mRemote.transact()会在服务端执行onTransact()回调,onTransact()回调则会去调用AMS.startActivity()

5、AMS.startActivity

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

public final int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
    enforceNotIsolatedCaller("startActivity");
    userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
            false, ALLOW_FULL_ONLY, "startActivity", null);

    return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
            resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
            profilerInfo, null, null, options, false, userId, null, null);
}

mStackSupervisor的数据类型为ActivityStackSupervisor

6、ASS.startActivityMayWait

final 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 config, Bundle options, boolean ignoreTargetSecurity, int userId, IActivityContainer iContainer, TaskRecord inTask) {
    ...
    boolean componentSpecified = intent.getComponent() != null;
    // 获得即将启动的Intent
    intent = new Intent(intent);

    // PackageManager解析出ActivityInfo,如果存在多个可供选择的Activity,则直接弹窗让用户选择
    ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags, profilerInfo, userId);

    ActivityContainer container = (ActivityContainer)iContainer;
    synchronized (mService) {

        // 获取Pid和Uid
        final int realCallingPid = Binder.getCallingPid();
        final int realCallingUid = Binder.getCallingUid();
        int callingPid;
        if (callingUid >= 0) {
            callingPid = -1;
        } else if (caller == null) {
            callingPid = realCallingPid;
            callingUid = realCallingUid;
        } else {
            callingPid = callingUid = -1;
        }

        final ActivityStack stack;
        if (container == null || container.mStack.isOnHomeDisplay()) {
            stack = mFocusedStack;
        } else {
            stack = container.mStack;
        }

        stack.mConfigWillChange = config != null && mService.mConfiguration.diff(config) != 0;

        final long origId = Binder.clearCallingIdentity();
        ...
        int res = startActivityLocked(caller, intent, resolvedType, aInfo,
                voiceSession, voiceInteractor, resultTo, resultWho,
                requestCode, callingPid, callingUid, callingPackage,
                realCallingPid, realCallingUid, startFlags, options, ignoreTargetSecurity,
                componentSpecified, null, container, inTask);
        ...
        return res;
    }
}

7、ASS.startActivityLocked

主要流程:参数设置、常规检查、权限检查、AppSwitch

startActivityLocked()如此多的函数入参,意味着该函数的执行场景非常多

函数入参 描述
caller Binder本地对象mToken
intent 启动Activity的Intent
revolvedType Intent的解析类型
aInfo Activity的静态信息类
voiceSession,voiceInteractor 语音相关的接口
resultTo 调用者Activity
resultWho 调用者Activity的字符串
requestCode 请求码
callingPid,callingUid 调用者的进程号和用户号
callingPackage 调用者包名
realCallingPid,realCallingUid
startFlags 启动Activity的Flag
options
ignoreTargetSecurity
componentSpecified
outActivity 记录启动的ActivityRecord
container
inTask 待启动Activity所在的任务
final int startActivityLocked(IApplicationThread caller, Intent intent, String resolvedType, ActivityInfo aInfo, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid, String callingPackage, int realCallingPid, int realCallingUid, int startFlags, Bundle options, boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity, ActivityContainer container, TaskRecord inTask) {
    int err = ActivityManager.START_SUCCESS;

    // 获取调用者的进程记录对象
    ProcessRecord callerApp = null;
    if (caller != null) {
        callerApp = mService.getRecordForAppLocked(caller);
        if (callerApp != null) {
            callingPid = callerApp.pid;
            callingUid = callerApp.info.uid;
        } else {
            err = ActivityManager.START_PERMISSION_DENIED;
        }
    }

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

    ActivityRecord sourceRecord = null;
    ActivityRecord resultRecord = null;
    if (resultTo != null) {
        // 获取调用者所在的Activity
        sourceRecord = isInAnyStackLocked(resultTo);
        if (sourceRecord != null) {
            if (requestCode >= 0 && !sourceRecord.finishing) {
                ... //requestCode = -1 则不进入
            }
        }
    }

    // 以下代码都是进行一些常规检查,如果不符合条件,则给定一个错误码,标记启动失败
    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;
    }
    if (err == ActivityManager.START_SUCCESS
            && !isCurrentProfileLocked(userId)
            && (aInfo.flags & FLAG_SHOW_FOR_ALL_USERS) == 0) {
        err = ActivityManager.START_NOT_CURRENT_USER_ACTIVITY;
    }

    ... // 省略与语音相关的常规检查

    // 如果错误码被标记上,表示上面的常规检查没有通过,需要结束Activity的启动过程。
    final ActivityStack resultStack = resultRecord == null ? null : resultRecord.task.stack;
    if (err != ActivityManager.START_SUCCESS) {
        if (resultRecord != null) {
            // 此处,如果resultRecord不为null,则需要告诉调用者启动失败了
            resultStack.sendActivityResultLocked(-1,
            resultRecord, resultWho, requestCode,
            Activity.RESULT_CANCELED, null);
        }
        ActivityOptions.abort(options);
        return err;
    }

    // 常规检查通过,又要开始进行一系列的权限检查,权限检查是通过abort这个变量来标记的
    boolean abort = false;
    final int startAnyPerm = mService.checkPermission(
            START_ANY_ACTIVITY, callingPid, callingUid);
    ... // 省略大量权限检查的代码
    if (abort) {
        if (resultRecord != null) {
            resultStack.sendActivityResultLocked(-1, resultRecord, resultWho, requestCode, Activity.RESULT_CANCELED, null);
       }
       ActivityOptions.abort(options);
       // 如果权限检查失败,会中断Activity的启动过程,但返回的却是START_SUCCESS
       return ActivityManager.START_SUCCESS;
    }

    // 创建Activity记录对象
    ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
            intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,
            requestCode, componentSpecified, voiceSession != null, this, container, options);
    if (outActivity != null) {
        outActivity[0] = r;
    }

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

    final ActivityStack stack = mFocusedStack;
    if (voiceSession == null && (stack.mResumedActivity == null
            || stack.mResumedActivity.info.applicationInfo.uid != callingUid)) {
        ... // AppSwitch相关的处理逻辑
    }
    if (mService.mDidAppSwitch) {
        mService.mAppSwitchesAllowedTime = 0;
    } else {
        mService.mDidAppSwitch = true;
    }

    //处理pendind Activity的启动, 这些Activity是由于app switch禁用从而被等待启动activity
    doPendingActivityLaunchesLocked(false);

    err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
            startFlags, true, options, inTask);

    if (err < 0) {
        notifyActivityDrawnForKeyguard();
    }
    return err;
}

startActivityLocked()的返回值会int类型,我们来列举其返回值的结果

返回值 描述
START_SUCCESS(0) 启动成功
START_INTENT_NOT_RESOLVED(-1) 无法解析Intent所请求的Activity
START_CLASS_NOT_FOUND(-2) 无法找到目标Activity的类
START_FORWARD_AND_REQUEST_CONFLICT(-3) 带RequestCode启动Activity时,存在的一种与resultTo冲突的场景
START_PERMISSION_DENIED(-4) 调用者没有获取启动Activity的授权
START_NOT_VOICE_COMPATIBLE(-7) 当前并不支持语音
START_NOT_CURRENT_USER_ACTIVITY(-8) 目标Activity并非对当前用户可见
START_SWITCHES_CANCELED(4) App Switch功能关闭时,需要将待启动的Activity推入Pending状态

8、ASS.startActivityUncheckedLocked

主要流程:

  1. Activity各种启动参数(Launcher Mode和Launcher Flag)的组合修正
  2. 处理目标Activity已经启动过的场景,只需要把其找出来,重新挪到前台显示即可
  3. 处理目标Activity不存在的场景,即该Activity没有被启动过,或者启动过后已经销毁的场景

startActivityUncheckedLocked()参数也比较多,大部分是前面已经介绍过,这里不重复出现

函数入参 描述
r 待启动的Activity记录信息,startActivityLocked()新建的ActivityRecord对象
sourceRecord 调用者的Activity记录信息,即当前还处于显示状态的ActivityRecord
doResume 表示是否要将Activity推入Resume状态,从startActivityLocked()传入进来的参数值为true
final int startActivityUncheckedLocked(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, Bundle options, TaskRecord inTask) {

    // 1、Activity各种启动参数(Launcher Mode和Launcher Flag)的组合修正
    final Intent intent = r.intent;
    final int callingUid = r.launchedFromUid;

    if (inTask != null && !inTask.inRecents) {
        inTask = null;
    }

    // 获取Activity的启动模式
    final boolean launchSingleTop = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP;
    final boolean launchSingleInstance = r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE;
    final boolean launchSingleTask = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK;

    // 处理启动参数FLAG_ACTIVITY_NEW_DOCUMENT
    int launchFlags = intent.getFlags();
    if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0 &&
            (launchSingleInstance || launchSingleTask)) {
        launchFlags &=
                ~(Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
    } else {
        ...
    }

    // 是否为后台启动任务的标志位
    final boolean launchTaskBehind = r.mLaunchTaskBehind
            && !launchSingleTask && !launchSingleInstance
            && (launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0;

    if (r.resultTo != null && (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0
            && r.resultTo.task.stack != null) {
        r.resultTo.task.stack.sendActivityResultLocked(-1,
                r.resultTo, r.resultWho, r.requestCode,
                Activity.RESULT_CANCELED, null);
        r.resultTo = null;
    }

    // 如果启动参数包含FLAG_ACTIVITY_NEW_DOCUMENT,而且又没有resultTo,则意味着要在一个新的任务中启动Activity
    if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0 && r.resultTo == null) {
        launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
    }

    if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
        if (launchTaskBehind
                || r.info.documentLaunchMode == ActivityInfo.DOCUMENT_LAUNCH_ALWAYS) {
            // 对于后台启动的新任务,可以多任务运行
            launchFlags |= Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
        }
    }

    // 如果设置了FLAG_ACTIVITY_NO_USER_ACTION,则该回调函数不会被调用
    mUserLeaving = (launchFlags & Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
    // 当本次不需要resume,则设置为延迟resume的状态
    if (!doResume) {
        r.delayedResume = true;
    }

    // FLAG_ACTIVITY_PREVIOUS_IS_TOP用于一些特殊的场景:待启动的Activity不会被作为栈顶
    // 换句话说,调用者希望待启动的Activity马上销毁,就会使用该启动参数
    ActivityRecord notTop =
            (launchFlags & Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP) != 0 ? r : null;

    ...// 省略 START_FLAG_ONLY_IF_NEEDED的处理逻辑

    boolean addingToTask = false;// 表示是否在传入的inTask中启动Actiivty,后面会根据实际情况重新设置该变量
    TaskRecord reuseTask = null;// 表示复用的任务,如果inTask存在,则inTask就可以作为reuseTask


    if (sourceRecord == null && inTask != null && inTask.stack != null) {
        ... 
    } else {
        inTask = null;
    }

    if (inTask == null) {
        // sourceRecord为null,表示调用者不是Activity
        if (sourceRecord == null) {
            //强制在新的任务中启动Activity
            if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) == 0 && inTask == null) {
                launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
            }
        } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
            // 如果调用者的启动模式为LAUNCH_SINGLE_INSTANCE,则需要在新的任务中启动新的Activity
            launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
        } else if (launchSingleInstance || launchSingleTask) {
            // 如果目标Activity的启动模式为singleInstance或SingleTask,则需要在新的任务中启动
            launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
        }
    }

    // 2、处理目标Activity已经启动过的场景,只需要把其找出来,重新挪到前台显示即可
    ActivityInfo newTaskInfo = null;
    Intent newTaskIntent = null;
    ActivityStack sourceStack;
    if (sourceRecord != null) {
        if (sourceRecord.finishing) {
            // 如果调用者已经处于销毁状态,那意味着其所在的任务也可能被销毁了
            // 待启动的Activity需要保留已有任务的信息,并强制在新的任务中启动
            if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
                launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
                newTaskInfo = sourceRecord.info;
                newTaskIntent = sourceRecord.task.intent;
            }
            sourceRecord = null;
            sourceStack = null;
        } else {
            // 当调用者Activity不为空,且不处于finishing状态,则其所在栈赋于sourceStack
            sourceStack = sourceRecord.task.stack;
        }
    } else {
        sourceStack = null;
    }

    boolean movedHome = false;
    ActivityStack targetStack;// 待启动Activity的宿主栈

    intent.setFlags(launchFlags);// 重新设置将修正后的launchFlags
    // 是否有动画是由启动参数FLAG_ACTIVITY_NO_ANIMATION决定的
    final boolean noAnimation = (launchFlags & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0;

    if (((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
            (launchFlags & Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
            || launchSingleInstance || launchSingleTask) {
        if (inTask == null && r.resultTo == null) {
            // 不是在当前任务中启动Activity
            // 则需要从mActivityDisplays开始查询是否有相应ActivityRecord
            ActivityRecord intentActivity = !launchSingleInstance ?
                    findTaskLocked(r) : findActivityLocked(intent, r.info);
            if (intentActivity != null) {
                // 如果找到目标Activity,则进入LOCK_TASK机制
                // 表明目标Activity所在的TaskRecord和TaskRecord所在的ActivityRecord就是宿主任务和宿主栈
                if (isLockTaskModeViolation(intentActivity.task,
                        (launchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))
                        == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))) {
                    return ActivityManager.START_RETURN_LOCK_TASK_MODE_VIOLATION;
                }
                if (r.task == null) {
                    r.task = intentActivity.task;
                }
                if (intentActivity.task.intent == null) {
                    intentActivity.task.setIntent(r);
                }
                // 设置目标栈targetStack
                targetStack = intentActivity.task.stack;
                targetStack.mLastPausedActivity = null;

                // 获取当前的焦点栈
                final ActivityStack focusStack = getFocusedStack();
                // 获取前可见的ActivityRecord
                ActivityRecord curTop = (focusStack == null)
                        ? null : focusStack.topRunningNonDelayedActivityLocked(notTop);
                boolean movedToFront = false;
                if (curTop != null && (curTop.task != intentActivity.task ||
                        curTop.task != focusStack.topTask())) {
                    // 当前可见的Activity与待启动的Activity不在同一个任务,需要将宿主栈挪到前台
                    r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
                    if (sourceRecord == null || (sourceStack.topActivity() != null &&
                            sourceStack.topActivity().task == sourceRecord.task)) {
                        if (launchTaskBehind && sourceRecord != null) {
                            intentActivity.setTaskToAffiliateWith(sourceRecord.task);
                        }
                        movedHome = true;
                        // 将目标Activity所在的任务挪到栈顶
                        targetStack.moveTaskToFrontLocked(intentActivity.task, noAnimation,
                                options, r.appTimeTracker, "bringingFoundTaskToFront");
                        movedToFront = true;
                        if ((launchFlags &
                                (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_TASK_ON_HOME))
                                == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_TASK_ON_HOME)) {
                            intentActivity.task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
                        }
                        options = null;
                    }
                }
                if (!movedToFront) {
                    targetStack.moveToFront("intentActivityFound");
                }

                if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
                    intentActivity = targetStack.resetTaskIfNeededLocked(intentActivity, r);
                }

                // 开始对launchFlags的调整
                if ((startFlags & ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
                    if (doResume) {
                        resumeTopActivitiesLocked(targetStack, null, options);
                        // 当没有启动至前台,则通知Keyguard
                        if (!movedToFront) {
                            notifyActivityDrawnForKeyguard();
                        }
                    } else {
                        ActivityOptions.abort(options);
                    }
                    return ActivityManager.START_RETURN_INTENT_TO_CALLER;
                }
                if ((launchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))
                        == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK)) {
                    reuseTask = intentActivity.task;
                    // 移除所有跟已存在的task有关联的activity
                    reuseTask.performClearTaskLocked();
                    reuseTask.setIntent(r);
                } else if ((launchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0
                        || launchSingleInstance || launchSingleTask) {
                    ActivityRecord top =
                            intentActivity.task.performClearTaskLocked(r, launchFlags);
                    if (top != null) {
                        if (top.frontOfTask) {
                            top.task.setIntent(r);
                        }
                        // 触发onNewIntent()
                        top.deliverNewIntentLocked(callingUid, r.intent, r.launchedFromPackage);
                    } else {
                        sourceRecord = intentActivity;
                        TaskRecord task = sourceRecord.task;
                        if (task != null && task.stack == null) {
                            targetStack = computeStackFocus(sourceRecord, false /* newTask */);
                            targetStack.addTask(
                                    task, !launchTaskBehind /* toTop */, false /* moving */);
                        }

                    }
                } else if (r.realActivity.equals(intentActivity.task.realActivity)) {
                    if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0 || launchSingleTop)
                            && intentActivity.realActivity.equals(r.realActivity)) {
                        if (intentActivity.frontOfTask) {
                            intentActivity.task.setIntent(r);
                        }
                        // 触发onNewIntent()
                        intentActivity.deliverNewIntentLocked(callingUid, r.intent,
                                r.launchedFromPackage);
                    } else if (!r.intent.filterEquals(intentActivity.task.intent)) {
                        addingToTask = true;
                        sourceRecord = intentActivity;
                    }
                } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
                    addingToTask = true;
                    sourceRecord = intentActivity;
                } else if (!intentActivity.task.rootWasReset) {
                    intentActivity.task.setIntent(r);
                }
                if (!addingToTask && reuseTask == null) {
                    if (doResume) {
                        targetStack.resumeTopActivityLocked(null, options);
                        if (!movedToFront) {
                            notifyActivityDrawnForKeyguard();
                        }
                    } else {
                        ActivityOptions.abort(options);
                    }
                    return ActivityManager.START_TASK_TO_FRONT;
                }
            }
        }
    }

    if (r.packageName != null) {
        // 包名不为null,则找到待启动的activity
        ActivityStack topStack = mFocusedStack;
        ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(notTop);
        if (top != null && r.resultTo == null) {
            if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
                if (top.app != null && top.app.thread != null) {
                    if ((launchFlags & Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
                        || launchSingleTop || launchSingleTask) {
                        topStack.mLastPausedActivity = null;
                        if (doResume) {
                            resumeTopActivitiesLocked();
                        }
                        ActivityOptions.abort(options);
                        if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
                        }
                        // 触发onNewIntent()
                        top.deliverNewIntentLocked(callingUid, r.intent, r.launchedFromPackage);
                        return ActivityManager.START_DELIVERED_TO_TOP;
                    }
                }
            }
        }

    } else {
        // 包名为null,则表示找不到待启动的Activity
        if (r.resultTo != null && r.resultTo.task.stack != null) {
            r.resultTo.task.stack.sendActivityResultLocked(-1, r.resultTo, r.resultWho,
                    r.requestCode, Activity.RESULT_CANCELED, null);
        }
        ActivityOptions.abort(options);
        return ActivityManager.START_CLASS_NOT_FOUND;
    }

    // 3、处理目标Activity不存在的场景,即该Activity没有被启动过,或者启动过后已经销毁的场景
    boolean newTask = false;
    boolean keepCurTransition = false;

    TaskRecord taskToAffiliate = launchTaskBehind && sourceRecord != null ?
            sourceRecord.task : null;

    if (r.resultTo == null && inTask == null && !addingToTask
            && (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
        // 该类情况表示要在一个新的任务中启动Activity
        newTask = true;
        targetStack = computeStackFocus(r, newTask);
        targetStack.moveToFront("startingNewTask");

        if (reuseTask == null) {
            // 如果不存在可以复用的任务,则新建一个
            r.setTask(targetStack.createTaskRecord(getNextTaskId(),
                    newTaskInfo != null ? newTaskInfo : r.info,
                    newTaskIntent != null ? newTaskIntent : intent,
                    voiceSession, voiceInteractor, !launchTaskBehind /* toTop */),
                    taskToAffiliate);
        } else {
            r.setTask(reuseTask, taskToAffiliate);
        }
        if (isLockTaskModeViolation(r.task)) {
            return ActivityManager.START_RETURN_LOCK_TASK_MODE_VIOLATION;
        }
        if (!movedHome) {
            if ((launchFlags &
                    (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_TASK_ON_HOME))
                    == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_TASK_ON_HOME)) {
                r.task.setTaskToReturnTo(HOME_ACTIVITY_TYPE);
            }
        }
    } else if (sourceRecord != null) {
        // 该类情况表示宿主栈就是调用者Activity所在的ActivityStack
        final TaskRecord sourceTask = sourceRecord.task;
        if (isLockTaskModeViolation(sourceTask)) {
            return ActivityManager.START_RETURN_LOCK_TASK_MODE_VIOLATION;
        }
        targetStack = sourceTask.stack;
        targetStack.moveToFront("sourceStackToFront");
        final TaskRecord topTask = targetStack.topTask();
        if (topTask != sourceTask) {
            targetStack.moveTaskToFrontLocked(sourceTask, noAnimation, options,
                    r.appTimeTracker, "sourceTaskToFront");
        }
        if (!addingToTask && (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
            ActivityRecord top = sourceTask.performClearTaskLocked(r, launchFlags);
            keepCurTransition = true;
            if (top != null) {
                //触发onNewIntent()
                top.deliverNewIntentLocked(callingUid, r.intent, r.launchedFromPackage);
                targetStack.mLastPausedActivity = null;
                if (doResume) {
                    targetStack.resumeTopActivityLocked(null);
                }
                ActivityOptions.abort(options);
                return ActivityManager.START_DELIVERED_TO_TOP;
            }
        } else if (!addingToTask &&
                (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
            final ActivityRecord top = sourceTask.findActivityInHistoryLocked(r);
            if (top != null) {
                final TaskRecord task = top.task;
                task.moveActivityToFrontLocked(top);
                top.updateOptionsLocked(options);
                //触发onNewIntent()
                top.deliverNewIntentLocked(callingUid, r.intent, r.launchedFromPackage);
                targetStack.mLastPausedActivity = null;
                if (doResume) {
                    targetStack.resumeTopActivityLocked(null);
                }
                return ActivityManager.START_DELIVERED_TO_TOP;
            }
        }
        r.setTask(sourceTask, null);
    } else if (inTask != null) {
        // 该类情况表示在指定的任务栈中启动Activity
        if (isLockTaskModeViolation(inTask)) {
            return ActivityManager.START_RETURN_LOCK_TASK_MODE_VIOLATION;
        }
        targetStack = inTask.stack;
        targetStack.moveTaskToFrontLocked(inTask, noAnimation, options, r.appTimeTracker,
                "inTaskToFront");

        ActivityRecord top = inTask.getTopActivity();
        if (top != null && top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
            if ((launchFlags & Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
                    || launchSingleTop || launchSingleTask) {
                if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
                    return ActivityManager.START_RETURN_INTENT_TO_CALLER;
                }
                //触发onNewIntent()
                top.deliverNewIntentLocked(callingUid, r.intent, r.launchedFromPackage);
                return ActivityManager.START_DELIVERED_TO_TOP;
            }
        }

        if (!addingToTask) {
            ActivityOptions.abort(options);
            return ActivityManager.START_TASK_TO_FRONT;
        }

        r.setTask(inTask, null);

    } else {
        // 该类情况表示既不是从一个Activity启动,也不是在新的任务中启动
        targetStack = computeStackFocus(r, newTask);
        targetStack.moveToFront("addingToTopTask");
        ActivityRecord prev = targetStack.topActivity();
        r.setTask(prev != null ? prev.task : targetStack.createTaskRecord(getNextTaskId(),
                        r.info, intent, null, null, true), null);
        mWindowManager.moveTaskToTop(r.task.taskId);
    }

    mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
            intent, r.getUriPermissionsLocked(), r.userId);

    if (sourceRecord != null && sourceRecord.isRecentsActivity()) {
        r.task.setTaskToReturnTo(RECENTS_ACTIVITY_TYPE);
    }

    targetStack.mLastPausedActivity = null;
    // 创建activity
    targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options);
    if (!launchTaskBehind) {
        mService.setFocusedActivityLocked(r, "startedActivity");
    }
    return ActivityManager.START_SUCCESS;
}

startActivityUncheckedLocked()的返回值会int类型,我们来列举其返回值的结果

返回值 描述
START_CLASS_NOT_FOUND(-2) 无法找到目标Activity的类
START_SUCCESS(0) 启动成功
START_RETURN_INTENT_TO_CALLER(1) 当启动参数中带有START_FLAG_ONLY_IF_NEEDED标志时,如果目标Activity就是当前的调用者,则返回该值,启动结束
START_TASK_TO_FRONT(2) 在已有任务中找到了目标Activity,则只需要把目标Activity挪到前台即可,启动结束
START_DELIVERED_TO_TOP(3) 目标Activity位于任务栈顶,则只需要将Intent派送到栈顶的Activity即可,启动结束
START_RETURN_LOCK_TASK_MODE_VIOLATION(5) 目标Activity的宿主任务处于LockTaskMode模式,且目标Activity的启动方式违背了LockTaskMode的规则,则不能启动目标Activity

9、AS.startActivityLocked

final void startActivityLocked(ActivityRecord r, boolean newTask, boolean doResume, boolean keepCurTransition, Bundle options) {
    TaskRecord rTask = r.task;
    final int taskId = rTask.taskId;
    if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {
        // 表示宿主栈中没有历史任务,或者强制要求在新的任务中启动Activity,需要将任务插入宿主栈顶
        insertTaskAtTop(rTask, r);
        mWindowManager.moveTaskToTop(taskId);
    }
    TaskRecord task = null;
    if (!newTask) {
        // 表示需要在一个已有的任务中启动Activity
        boolean startIt = true;
        for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
            // 从上往下遍历宿主栈中的所有任务,找到目标任务的位置
            task = mTaskHistory.get(taskNdx);
            if (task.getTopActivity() == null) {
                continue;
            }
            if (task == r.task) {
                if (!startIt) {
                    task.addActivityToTop(r);
                    r.putInHistory();
                    mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
                            r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
                            (r.info.flags & ActivityInfo.FLAG_SHOW_FOR_ALL_USERS) != 0,
                            r.userId, r.info.configChanges, task.voiceSession != null,
                            r.mLaunchTaskBehind);
                    ActivityOptions.abort(options);
                    return;
                }
                break;
            } else if (task.numFullscreen > 0) {
                startIt = false;
            }
        }
    }

    if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) {
        mStackSupervisor.mUserLeaving = false;
    }

    task = r.task;
    task.addActivityToTop(r);
    task.setFrontOfTask();// 将一个新的ActivityRecord添加到任务栈顶后,需要重新调整FrontOfTask

    r.putInHistory();// 标记ActivityRecord已经放置到宿主栈中
    mActivityTrigger.activityStartTrigger(r.intent, r.info, r.appInfo);
    if (!isHomeStack() || numActivities() > 0) {
        // 表示宿主栈中已经有Activity,将待启动的Activity绑定到窗口上
        boolean showStartingIcon = newTask;
        ProcessRecord proc = r.app;
        if (proc == null) {
            proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
        }

        if (proc == null || proc.thread == null) {
            showStartingIcon = true;
        }
        if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, keepCurTransition);
            mNoAnimActivities.add(r);
        } else {
            mWindowManager.prepareAppTransition(newTask
                    ? r.mLaunchTaskBehind
                            ? AppTransition.TRANSIT_TASK_OPEN_BEHIND
                            : AppTransition.TRANSIT_TASK_OPEN
                    : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
            mNoAnimActivities.remove(r);
        }
        mWindowManager.addAppToken(task.mActivities.indexOf(r),
                r.appToken, r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
                (r.info.flags & ActivityInfo.FLAG_SHOW_FOR_ALL_USERS) != 0, r.userId,
                r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind);
        boolean doShow = true;
        if (newTask) {
            if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
                resetTaskIfNeededLocked(r, r);
                doShow = topRunningNonDelayedActivityLocked(null) == r;
            }
        } else if (options != null && new ActivityOptions(options).getAnimationType()
                == ActivityOptions.ANIM_SCENE_TRANSITION) {
            doShow = false;
        }
        if (r.mLaunchTaskBehind) {
            mWindowManager.setAppVisibility(r.appToken, true);
            ensureActivitiesVisibleLocked(null, 0);
        } else if (SHOW_APP_STARTING_PREVIEW && doShow) {
            ActivityRecord prev = mResumedActivity;
            if (prev != null) {
                if (prev.task != r.task) {
                    prev = null;
                }
                else if (prev.nowVisible) {
                    prev = null;
                }
            }

            mWindowManager.setAppStartingWindow(
                    r.appToken, r.packageName, r.theme,
                    mService.compatibilityInfoForPackageLocked(
                             r.info.applicationInfo), r.nonLocalizedLabel,
                    r.labelRes, r.icon, r.logo, r.windowFlags,
                    prev != null ? prev.appToken : null, showStartingIcon);
            r.mStartingWindowShown = true;
        }
    } else {
        // 进入该分支,表示当前的宿主栈中还没有任何Activity,只是将待启动的Activity绑定到窗口上
        mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
                r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
                (r.info.flags & ActivityInfo.FLAG_SHOW_FOR_ALL_USERS) != 0, r.userId,
                r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind);
        ActivityOptions.abort(options);
        options = null;
    }

    if (doResume) {
        mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
    }
}

10、ASS.resumeTopActivitiesLocked

boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target, Bundle targetOptions) {
    if (targetStack == null) {
        targetStack = mFocusedStack;
    }

    boolean result = false;
    if (isFrontStack(targetStack)) {
        // 转交ActivityStack完成待启动Activity的显示
        result = targetStack.resumeTopActivityLocked(target, targetOptions);
    }
    // 对所有显示设备上的ActivityStack都进行相同的操作
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        final ArrayList stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
        for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
            final ActivityStack stack = stacks.get(stackNdx);
            if (stack == targetStack) {
                continue;
            }
            // 转由其他显示设备的ActivityStack完成待启动Activity的显示
            if (isFrontStack(stack)) {
                stack.resumeTopActivityLocked(null);
            }
        }
    }
    return result;
}

11、AS.resumeTopActivityLocked

final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
    if (mStackSupervisor.inResumeTopActivity) {
        return false; //防止递归启动
    }

    boolean result = false;
    try {
        mStackSupervisor.inResumeTopActivity = true;
        if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) {
            mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN;
            mService.updateSleepIfNeededLocked();
        }
        result = resumeTopActivityInnerLocked(prev, options);
    } finally {
        mStackSupervisor.inResumeTopActivity = false;
    }
    return result;
}

12、AS.resumeTopActivityInnerLocked

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
    ... // 如果系统还未启动完毕,那AMS还不能正常工作,所以也不能显示Activity

    ActivityRecord parent = mActivityContainer.mParentActivity;
    if ((parent != null && parent.state != ActivityState.RESUMED) ||
            !mActivityContainer.isAttachedLocked()) {
        return false;
    }
    cancelInitializingActivities();

    // 找到当前AS的栈顶
    final ActivityRecord next = topRunningActivityLocked(null);
    final boolean userLeaving = mStackSupervisor.mUserLeaving;
    mStackSupervisor.mUserLeaving = false;

    final TaskRecord prevTask = prev != null ? prev.task : null;
    if (next == null) {
        // 进入该条件分支表示AS中没有要显示的Activity
        final String reason = "noMoreActivities";
        if (!mFullscreen) {
            // 当前AS不是全屏显示,则需要将焦点切换到下一个待显示的AS
            final ActivityStack stack = getNextVisibleStackLocked();
            if (adjustFocusToNextVisibleStackLocked(stack, reason)) {
                return mStackSupervisor.resumeTopActivitiesLocked(stack, prev, null);
            }
        }
        ActivityOptions.abort(options);
        final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
                HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
        // 启动home桌面activity
        return isOnHomeDisplay() &&
                mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, reason);
    }

    next.delayedResume = false;

    if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
                mStackSupervisor.allResumedActivitiesComplete()) {
        // 当前正在显示的Activity正好就是下一个待显示的Activity,就中断对待显示ActivityRecord的调度
        mWindowManager.executeAppTransition();
        mNoAnimActivities.clear();
        ActivityOptions.abort(options);
        return false;
    }

    final TaskRecord nextTask = next.task;
    if (prevTask != null && prevTask.stack == this &&
            prevTask.isOverHomeStack() && prev.finishing && prev.frontOfTask) {
        if (prevTask == nextTask) {
            prevTask.setFrontOfTask();
        } else if (prevTask != topTask()) {
            final int taskNdx = mTaskHistory.indexOf(prevTask) + 1;
            mTaskHistory.get(taskNdx).setTaskToReturnTo(HOME_ACTIVITY_TYPE);
        } else if (!isOnHomeDisplay()) {
            return false;
        } else if (!isHomeStack()){
            final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
                    HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
            return isOnHomeDisplay() &&
                    mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, "prevFinished");
        }
    }

    if (mService.isSleepingOrShuttingDown()
            && mLastPausedActivity == next
            && mStackSupervisor.allPausedActivitiesComplete()) {
        // 系统进入休眠状态,当前AS的栈顶Activity已经处于Paused状态,中断对待显示Activity的调度    
        mWindowManager.executeAppTransition();
        mNoAnimActivities.clear();
        ActivityOptions.abort(options);
        return false;
    }

    if (mService.mStartedUsers.get(next.userId) == null) {
        return false; // 拥有该activity的用户没有启动则直接返回
    }

    mStackSupervisor.mStoppingActivities.remove(next);
    mStackSupervisor.mGoingToSleepActivities.remove(next);
    next.sleeping = false;
    mStackSupervisor.mWaitingVisibleActivities.remove(next);

    mActivityTrigger.activityResumeTrigger(next.intent, next.info, next.appInfo);

    if (!mStackSupervisor.allPausedActivitiesComplete()) {
        return false; //当正处于暂停activity,则直接返回
    }

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

    // 表示可以在当前显示的Activity执行Pausing时,同时进行Resume操作
    boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
    // 将后台AS中的Activity迁移到Pausing状态
    boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
    if (mResumedActivity != null) {
        // 将当前AS中正在显示的Activity迁移到Pausing状态
        pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
    }
    if (pausing) {
        if (next.app != null && next.app.thread != null) {
            mService.updateLruProcessLocked(next.app, true, null);
        }
        return true;
    }

    if (mService.isSleeping() && mLastNoHistoryActivity != null &&
            !mLastNoHistoryActivity.finishing) {
        requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED,
                null, "resume-no-history", false);
        mLastNoHistoryActivity = null;
    }

    if (prev != null && prev != next) {
        if (!mStackSupervisor.mWaitingVisibleActivities.contains(prev)
                && next != null && !next.nowVisible) {
            mStackSupervisor.mWaitingVisibleActivities.add(prev);
        } else {
            if (prev.finishing) {
                mWindowManager.setAppVisibility(prev.appToken, false);
            }
        }
    }

    AppGlobals.getPackageManager().setPackageStoppedState(
            next.packageName, false, next.userId);

    boolean anim = true;
    if (mIsAnimationBoostEnabled == true && mPerf == null) {
        mPerf = new BoostFramework();
    }
    if (prev != null) {
        if (prev.finishing) {
            if (mNoAnimActivities.contains(prev)) {
                anim = false;
                mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
            } else {
                mWindowManager.prepareAppTransition(prev.task == next.task
                        ? AppTransition.TRANSIT_ACTIVITY_CLOSE
                        : AppTransition.TRANSIT_TASK_CLOSE, false);
                if(prev.task != next.task && mPerf != null) {
                   mPerf.perfLockAcquire(aBoostTimeOut, aBoostParamVal);
                }
            }
            mWindowManager.setAppWillBeHidden(prev.appToken);
            mWindowManager.setAppVisibility(prev.appToken, false);
        } else {
            if (mNoAnimActivities.contains(next)) {
                anim = false;
                mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
            } else {
                mWindowManager.prepareAppTransition(prev.task == next.task
                        ? AppTransition.TRANSIT_ACTIVITY_OPEN
                        : next.mLaunchTaskBehind
                                ? AppTransition.TRANSIT_TASK_OPEN_BEHIND
                                : AppTransition.TRANSIT_TASK_OPEN, false);
                if(prev.task != next.task && mPerf != null) {
                    mPerf.perfLockAcquire(aBoostTimeOut, aBoostParamVal);
                }
            }
        }
    } else {
        if (mNoAnimActivities.contains(next)) {
            anim = false;
            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
        } else {
            mWindowManager.prepareAppTransition(AppTransition.TRANSIT_ACTIVITY_OPEN, false);
        }
    }

    Bundle resumeAnimOptions = null;
    if (anim) {
        ActivityOptions opts = next.getOptionsForTargetActivityLocked();
        if (opts != null) {
            resumeAnimOptions = opts.toBundle();
        }
        next.applyOptionsLocked();
    } else {
        next.clearOptionsLocked();
    }

    ActivityStack lastStack = mStackSupervisor.getLastStack();
    // 进程已存在的情况
    if (next.app != null && next.app.thread != null) {
        // activity正在成为可见
        mWindowManager.setAppVisibility(next.appToken, true);

        next.startLaunchTickingLocked();

        ActivityRecord lastResumedActivity = lastStack == null ? null :lastStack.mResumedActivity;
        ActivityState lastState = next.state;

        mService.updateCpuStats();
        // 设置Activity状态为resumed
        next.state = ActivityState.RESUMED;
        mResumedActivity = next;
        next.task.touchActiveTime();
        mRecentTasks.addLocked(next.task);
        mService.updateLruProcessLocked(next.app, true, null);
        updateLRUListLocked(next);
        mService.updateOomAdjLocked();

        boolean notUpdated = true;
        if (mStackSupervisor.isFrontStack(this)) {
            Configuration config = mWindowManager.updateOrientationFromAppTokens(
                    mService.mConfiguration,
                    next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
            if (config != null) {
                next.frozenBeforeDestroy = true;
            }
            notUpdated = !mService.updateConfigurationLocked(config, next, false, false);
        }

        if (notUpdated) {
            ActivityRecord nextNext = topRunningActivityLocked(null);

            if (nextNext != next) {
                mStackSupervisor.scheduleResumeTopActivities();
            }
            if (mStackSupervisor.reportResumedActivityLocked(next)) {
                mNoAnimActivities.clear();
                return true;
            }
            return false;
        }

        try {
            // 分发所有pending结果
            ArrayList a = next.results;
            if (a != null) {
                final int N = a.size();
                if (!next.finishing && N > 0) {
                    next.app.thread.scheduleSendResult(next.appToken, a);
                }
            }

            if (next.newIntents != null) {
                next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
            }

            next.sleeping = false;
            mService.showAskCompatModeDialogLocked(next);
            next.app.pendingUiClean = true;
            next.app.forceProcessStateUpTo(mService.mTopProcessState);
            next.clearOptionsLocked();
            //触发onResume()
            next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState,
                    mService.isNextTransitionForward(), resumeAnimOptions);

            mStackSupervisor.checkReadyForSleepLocked();

        } catch (Exception e) {
            ...
            return true;
        }
        next.visible = true;
        completeResumeLocked(next);
        next.stopped = false;

    } else {
        if (!next.hasBeenLaunched) {
            next.hasBeenLaunched = true;
        } else {
            if (SHOW_APP_STARTING_PREVIEW) {
                mWindowManager.setAppStartingWindow(
                        next.appToken, next.packageName, next.theme,
                        mService.compatibilityInfoForPackageLocked(
                                next.info.applicationInfo),
                        next.nonLocalizedLabel,
                        next.labelRes, next.icon, next.logo, next.windowFlags,
                        null, true);
            }
        }
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
    }
    return true;
}

13、ASS.startSpecificActivityLocked

主要作用:如果宿主进程不存在,则创建新的进程

void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
    ProcessRecord app = mService.getProcessRecordLocked(r.processName,
            r.info.applicationInfo.uid, true);

    r.task.stack.setLaunchTime(r);

    if (app != null && app.thread != null) {
        try {
            if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
                    || !"android".equals(r.info.packageName)) {
                app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
                        mService.mProcessStats);
            }
            // 真正的启动Activity
            realStartActivityLocked(r, app, andResume, checkConfig);
            return;
        } catch (RemoteException e) {
            Slog.w(TAG, "Exception when starting activity "
                    + r.intent.getComponent().flattenToShortString(), e);
        }

    }
    // 启动一个新的应用进程
    mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
            "activity", r.intent.getComponent(), false, false, true);
}

14、ASS.realStartActivityLocked

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

    if (andResume) {
        r.startFreezingScreenLocked(app, 0);
        mWindowManager.setAppVisibility(r.appToken, true);
        // 调度启动ticks用以收集应用启动慢的信息
        r.startLaunchTickingLocked();
    }

    if (checkConfig) {
        Configuration config = mWindowManager.updateOrientationFromAppTokens(
                mService.mConfiguration,
                r.mayFreezeScreenLocked(app) ? r.appToken : null);
        // 更新Configuration
        mService.updateConfigurationLocked(config, r, false, false);
    }

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

    int idx = app.activities.indexOf(r);
    if (idx < 0) {
        app.activities.add(r);
    }
    mService.updateLruProcessLocked(app, true, null);
    mService.updateOomAdjLocked();

    final TaskRecord task = r.task;
    if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE ||
            task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) {
        setLockTaskModeLocked(task, LOCK_TASK_MODE_LOCKED, "mLockTaskAuth==LAUNCHABLE", false);
    }

    final ActivityStack stack = task.stack;
    try {
        if (app.thread == null) {
            throw new RemoteException();
        }
        List results = null;
        List newIntents = null;
        if (andResume) {
            results = r.results;
            newIntents = r.newIntents;
        }
        if (r.isHomeActivity() && r.isNotResolverActivity()) {
            // home进程是该栈的根进程
            mService.mHomeProcess = task.mActivities.get(0).app;
        }
        mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
        ...

        if (andResume) {
            app.hasShownUi = true;
            app.pendingUiClean = true;
        }
        // 将该进程设置为前台进程PROCESS_STATE_TOP
        app.forceProcessStateUpTo(mService.mTopProcessState);
        // 正在启动Activity
        app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
                new Configuration(stack.mOverrideConfig), r.compat, r.launchedFromPackage,
                task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
                newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);

    } catch (RemoteException e) {
        if (r.launchFailed) {
            // 第二次启动失败,则结束该activity
            mService.appDiedLocked(app);
            stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
                    "2nd-crash", false);
            return false;
        }
        // 这是第一个启动失败,则重启进程
        app.activities.remove(r);
        throw e;
    }

    // 将该进程加入到mLRUActivities队列顶部
    stack.updateLRUListLocked(r);

    if (andResume) {
        // 启动过程的一部分
        stack.minimalResumeActivityLocked(r);
    } else {
        r.state = STOPPED;
        r.stopped = true;
    }

    if (isFrontStack(stack)) {
        // 当系统发生更新时,只会执行一次的用户向导
        mService.startSetupActivityLocked();
    }
    // 更新所有与该Activity具有绑定关系的Service连接
    mService.mServices.updateServiceConnectionActivitiesLocked(r.app);

    return true;
}

15、ATP.scheduleLaunchActivity

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident, ActivityInfo info, Configuration curConfig, Configuration overrideConfig, CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state, PersistableBundle persistentState, List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents, boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) throws RemoteException {
     Parcel data = Parcel.obtain();
     data.writeInterfaceToken(IApplicationThread.descriptor);
     intent.writeToParcel(data, 0);
     data.writeStrongBinder(token);
     data.writeInt(ident);
     info.writeToParcel(data, 0);
     curConfig.writeToParcel(data, 0);
     if (overrideConfig != null) {
         data.writeInt(1);
         overrideConfig.writeToParcel(data, 0);
     } else {
         data.writeInt(0);
     }
     compatInfo.writeToParcel(data, 0);
     data.writeString(referrer);
     data.writeStrongBinder(voiceInteractor != null ? voiceInteractor.asBinder() : null);
     data.writeInt(procState);
     data.writeBundle(state);
     data.writePersistableBundle(persistentState);
     data.writeTypedList(pendingResults);
     data.writeTypedList(pendingNewIntents);
     data.writeInt(notResumed ? 1 : 0);
     data.writeInt(isForward ? 1 : 0);
     if (profilerInfo != null) {
         data.writeInt(1);
         profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
     } else {
         data.writeInt(0);
     }
     mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,
             IBinder.FLAG_ONEWAY);
     data.recycle();
 }

由Binder中AIDL知识可知,mRemote.transact()会在服务端执行onTransact()回调,onTransact()回调则会去调用AT.scheduleLaunchActivity()

16、AT.scheduleLaunchActivity

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident, ActivityInfo info, Configuration curConfig, Configuration overrideConfig, CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state, PersistableBundle persistentState, List pendingResults, List pendingNewIntents, boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {

     updateProcessState(procState, false);

     ActivityClientRecord r = new ActivityClientRecord();

     r.token = token;
     r.ident = ident;
     r.intent = intent;
     r.referrer = referrer;
     r.voiceInteractor = voiceInteractor;
     r.activityInfo = info;
     r.compatInfo = compatInfo;
     r.state = state;
     r.persistentState = persistentState;

     r.pendingResults = pendingResults;
     r.pendingIntents = pendingNewIntents;

     r.startsNotResumed = notResumed;
     r.isForward = isForward;

     r.profilerInfo = profilerInfo;

     r.overrideConfig = overrideConfig;
     updatePendingConfiguration(curConfig);
     sendMessage(H.LAUNCH_ACTIVITY, r);
 }

17、H.handleMessage

public void handleMessage(Message msg) {
    switch (msg.what) {
        case LAUNCH_ACTIVITY: {
            final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
            r.packageInfo = getPackageInfoNoCheck(
                    r.activityInfo.applicationInfo, r.compatInfo);
            handleLaunchActivity(r, null);
        } break;
        ...
    }
}

18、ActivityThread.handleLaunchActivity

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    unscheduleGcIdler();
    mSomeActivitiesChanged = true;

    // 最终回调目标Activity的onConfigurationChanged()
    handleConfigurationChanged(null, null);
    // 初始化wms
    WindowManagerGlobal.initialize();
    // 最终回调目标Activity的onCreate
    Activity a = performLaunchActivity(r, customIntent);
    if (a != null) {
        r.createdConfig = new Configuration(mConfiguration);
        Bundle oldState = r.state;
        // 最终回调目标Activity的onStart,onResume
        handleResumeActivity(r.token, false, r.isForward,
                !r.activity.mFinished && !r.startsNotResumed);

        if (!r.activity.mFinished && r.startsNotResumed) {
            r.activity.mCalled = false;
            mInstrumentation.callActivityOnPause(r.activity);
            r.paused = true;
        }
    } else {
        // 存在error则停止该Activity
        ActivityManagerNative.getDefault()
            .finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
    }
}

19、ActivityThread.performLaunchActivity

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

    ActivityInfo aInfo = r.activityInfo;
    if (r.packageInfo == null) {
        r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
                Context.CONTEXT_INCLUDE_CODE);
    }

    ComponentName component = r.intent.getComponent();
    if (component == null) {
        component = r.intent.resolveActivity(
            mInitialApplication.getPackageManager());
        r.intent.setComponent(component);
    }

    if (r.activityInfo.targetActivity != null) {
        component = new ComponentName(r.activityInfo.packageName,
                r.activityInfo.targetActivity);
    }

    Activity activity = null;
    try {
        java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
        activity = mInstrumentation.newActivity(
                cl, component.getClassName(), r.intent);
        StrictMode.incrementExpectedActivityCount(activity.getClass());
        r.intent.setExtrasClassLoader(cl);
        r.intent.prepareToEnterProcess();
        if (r.state != null) {
            r.state.setClassLoader(cl);
        }
    } catch (Exception e) {
        ...
    }

    try {
        // 创建Application对象
        Application app = r.packageInfo.makeApplication(false, mInstrumentation);

        if (activity != null) {
            Context appContext = createBaseContextForActivity(r, activity);
            CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
            Configuration config = new Configuration(mCompatConfiguration);

            activity.attach(appContext, this, getInstrumentation(), r.token,
                    r.ident, app, r.intent, r.activityInfo, title, r.parent,
                    r.embeddedID, r.lastNonConfigurationInstances, config,
                    r.referrer, r.voiceInteractor);

            if (customIntent != null) {
                activity.mIntent = customIntent;
            }
            r.lastNonConfigurationInstances = null;
            activity.mStartedActivity = false;
            int theme = r.activityInfo.getThemeResource();
            if (theme != 0) {
                activity.setTheme(theme);
            }

            activity.mCalled = false;
            if (r.isPersistable()) {
                mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
            } else {
                mInstrumentation.callActivityOnCreate(activity, r.state);
            }
            ...
            r.activity = activity;
            r.stopped = true;
            if (!r.activity.mFinished) {
                activity.performStart();
                r.stopped = false;
            }
            if (!r.activity.mFinished) {
                if (r.isPersistable()) {
                    if (r.state != null || r.persistentState != null) {
                        mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
                                r.persistentState);
                    }
                } else if (r.state != null) {
                    mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
                }
            }
            if (!r.activity.mFinished) {
                activity.mCalled = false;
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnPostCreate(activity, r.state,
                            r.persistentState);
                } else {
                    mInstrumentation.callActivityOnPostCreate(activity, r.state);
                }
                ...
            }
        }
        r.paused = true;

        mActivities.put(r.token, r);

    }  catch (Exception e) {
        ...
    }

    return activity;
}

结语

Activity的启动流程很复杂,文章主要是抓住了主干来进行分析。文章多处借鉴别人的分析结果,综合有关信息完成的代码解释。其实Activity的启动的分支判断特别复杂,还有很多分支是没有进行分析的,建议想去了解某个分支的朋友可以用调试模式去代码中跑着看。

你可能感兴趣的:(android,activity启动)