Android筑基——Activity的启动过程之同进程在一个Activity中启动另一个Activity(基于api21)

1. 前言

本文基于Android 5.0的源码,分析Android中Activity的启动过程。

参与 Activity 启动的角色关系图如下:

在这里插入图片描述

Activity 启动过程时序图如下:

在这里插入图片描述

2. 正文

本文分析的场景是在一个 MainActivity 中启动同进程的 SecondActivity

2.1 Activity类的startActivity()方法

startActivity()的方法有两种:

  • 第一种方式是在 Activity 中直接调用的startActivity()方法,代码为MainActivity.this.startActivity(intent),这种方式会直接调用Activity类中的startActivity()方法,
    @Override
    public void startActivity(Intent intent) {
        this.startActivity(intent, null);

然后调用了

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

然后调用了

   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( // 发送结果,即onActivityResult会被调用 
                    mToken, mEmbeddedID, requestCode, ar.getResultCode(),
                    ar.getResultData());
            }
        } else {
            ...
        }
    }

这里首先要判断mParent == null是否为true,mParent顾名思义就是当前Activity的父Activity,而我们的ActivityMainActivity,它没有父类的Activity,所以这里的mParent == null的结果是true,实际上,mParent常用在ActivityGroup中,而ActivityGroup已经废弃(Added in API level 1 Deprecated since API level 13,代替的是FragmentFragmentManager的API).进入了if语句里面,看一下,往下走是调用的InstrumentationexecStartActivity()方法.

  • 第二种方式是直接调用非ActivityContext类的startActivity()方法,代码为getApplicationContext().startActivity(intent).这种方式会调用Context类的startActivity()方法,但这是个abstract方法,它的实现是在ContextWrapper类中,这是一个包装类,估计不干什么活儿.好了,来看一下Context类的startActivity()方法:
	@Override
    public void startActivity(Intent intent) {
        mBase.startActivity(intent);
    }

这里的mBase其实是ContextImpl对象,所以要继续看ContextImpl类中的startActivity(intent)方法

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

然后调用了

 	@Override
    public void startActivity(Intent intent, Bundle options) {
        warnIfCallingFromSystemProcess();
        if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
            throw new AndroidRuntimeException(
                    "Calling startActivity() from outside of an Activity "
                    + " context requires the FLAG_ACTIVITY_NEW_TASK flag."
                    + " Is this really what you want?");
        }
        mMainThread.getInstrumentation().execStartActivity(
            getOuterContext(), mMainThread.getApplicationThread(), null,
            (Activity)null, intent, -1, options);
    }

可以看到启动的Activity没有Activity栈,因此不能以standard方式启动,必须加上FLAG_ACTIVITY_NEW_TASK这个Flag,否则会报异常.
可以看到最终的调用也是InstrumentationexecStartActivity()方法.

本次我们分析的是第一种方式:

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
MainActivity.this.startActivity(intent);

2.2 Instrumentation类的execStartActivity()方法

Instrumentation类是用于监控应用和系统的交互的,用来辅助Activity完成启动Activity的过程.
来看一下它的execStartActivity()方法,这里的参数:

  • Context who = MainActivity.this,
  • IBinder contextThread = mMainThread.getApplicationThread(),这是一个ApplicationThread对象,其中mMainThread是在Activity的attach()方法中,进行初始化的
  • IBinder token = mToken,其中mToken也是在Activity的attach()方法中,进行初始化的.这是一个内部的token,用来标识正在启动Activity的系统,可能是null,
  • Activity target = MainActivity.this,发起启动的Activity
  • Intent intent = intent,即new Intent(MainActivity.this, SecondActivity.class);
  • requestCode = -1,
  • options = null.
    public ActivityResult execStartActivity(
            Context who, IBinder contextThread, IBinder token, Activity target,
            Intent intent, int requestCode, Bundle options) {
        // 核心功能在这个whoThread中完成,其内部scheduleLaunchActivity方法用于完成activity的打开 
        IApplicationThread whoThread = (IApplicationThread) contextThread; 
        // 这里 List<ActivityMonitor> mActivityMonitors 是一个 ActivityMonitor 的集合。
        // ActivityMonitor 是 Google 为了InstrumentationTest而加入的一个工具类。
        // 所以,不进行测试的话,不会走进这个分支。
        if (mActivityMonitors != null) {
            synchronized (mSync) {
                final int N = mActivityMonitors.size();
                for (int i=0; i<N; i++) {
                    final ActivityMonitor am = mActivityMonitors.get(i);
                    if (am.match(who, null, intent)) {
                        am.mHits++;
                        if (am.isBlocking()) {
                            return requestCode >= 0 ? am.getResult() : null;
                        }
                        break;
                    }
                }
            }
        }
        try {
            // 通过Binder向AMS发请求,来启动Activity
            int result = ActivityManagerNative.getDefault()
                .startActivity(whoThread, who.getBasePackageName(), intent,
                        intent.resolveTypeIfNeeded(who.getContentResolver()),
                        token, target != null ? target.mEmbeddedID : null,
                        requestCode, 0, null, options);
            // 检查结果:启动 Activity 成功这个方法就不执行什么操作;只有在有问题时,这个方法会抛出异常。
            // 看一下这个方法:初学时的我们,大概都会看到其中的一些异常。
            checkStartActivityResult(result, intent);
        } catch (RemoteException e) {
        }
        return null;
    }

这里面调用了ActivityManagerNative.getDefault().startActivity()方法.进入到ActivityManagerNative类中,看到ActivityManagerNative.getDefault()获取到的是一个IActivityManager对象.

    static public IActivityManager getDefault() {
        return gDefault.get();
    }

gDefault的定义如下:

  private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() {
        protected IActivityManager create() {
			// Returns a reference to a service with the given name
            IBinder b = ServiceManager.getService("activity");
            if (false) {
                Log.v("ActivityManager", "default service binder = " + b);
            }
            IActivityManager am = asInterface(b);
            if (false) {
                Log.v("ActivityManager", "default service = " + am);
            }
            return am;
        }
    };

在这个方法中,使用单例保存了ActivityManagerService的代理对象.所以getDefault()方法获取到的是ActivityManagerService的代理对象.

ActivityManagerNative类是一个抽象类,继承于Binder,实现了IActivityManager接口,在ActivityManagerNative这个编译单元里还有一个ActivityManagerProxy类,也实现了IActivityManager这个接口,但ActivityManagerProxy并不是ActivityManagerNative的内部类。它们之间是什么关系?

IActivityManager是一个IInterface,它代表了远程Service有什么能力,ActivityManagerNative指的是Binder本地对象(类似AIDL工具生成的Stub类),这个类是抽象类,它的实现是ActivityManagerService;因此对于AMS的最终操作都会进入ActivityManagerService这个真正实现;ActivityManagerNative.java这个编译单元里面有一个非公开类ActivityManagerProxy,它代表的是Binder代理对象。ActivityManager是一个管理类。

调用ActivityManagerService的代理对象的startActivity()方法,实际上调用的是ActivityManagerServicestartActivity()方法.

2.3 ActivityManagerService类的startActivity()方法

  • IApplicationThread caller = mMainThread.getApplicationThread()类型转换得到的IApplicationThread对象,
  • String callingPackage = 当前的context.getBasePackageName()
  • Intent intent = intent,即new Intent(MainActivity.this, SecondActivity.class);
  • String resolvedType,intent 的 MIME type
  • IBinder resultTo = mToken
  • String resultWho = mEmbeddedID,这个值是在 Activityattach 方法中赋值的。
  • int requestCode = -1
  • int startFlags = 0
  • ProfilerInfo profilerInfo = null
  • Bundle options = null
    @Override
    public final int startActivity(IApplicationThread caller, String callingPackage,
            Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
            int startFlags, ProfilerInfo profilerInfo, Bundle options) {
        return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
            resultWho, requestCode, startFlags, profilerInfo, options,
            UserHandle.getCallingUserId());
    }

接着还是这个类中,调用 startActivityAsUser 方法,只是新增了一个 int userId 参数而已:

  • IApplicationThread caller, mMainThread.getApplicationThread()类型转换得到的IApplicationThread对象
  • String callingPackage, 当前的context.getBasePackageName()
  • Intent intent, intent,即new Intent(MainActivity.this, SecondActivity.class);
  • String resolvedType ,intent 的 MIME type,
  • IBinder resultTo, mToken
  • String resultWho, mEmbeddedID,这个值是在 Activityattach 方法中赋值的。
  • int requestCode, -1
  • int startFlags, 0
  • ProfilerInfo profilerInfo, null
  • Bundle options, null
  • int userId, UserHandle.getCallingUserId()
    /** Run all ActivityStacks through this */
    ActivityStackSupervisor mStackSupervisor;
    
    @Override
    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) {
        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, userId, null, null); // 调用这里
    }

mStackSupervisorActivityStackSupervisor对象,运行所有的 Activity 都要通过这个对象。它的初始化是在ActivityManagerService的构造函数中。关于 ActivityStatckActivityStackSupervisor 的详细介绍,可以查看:四大组件之ActivityRecord

2.4 ActivityStackSupervisor类的startActivityMayWait()方法

主要完成的是通过 resolveActivity 来获取 ActivityInfo 的信息,MayWait 的意思是当存在多个可供选择的 Activity 时,则会向用户弹出 resolveActivity。

  • IApplicationThread caller, mMainThread.getApplicationThread()类型转换得到的IApplicationThread对象,ApplicationThreadProxy 对象
  • int callingUid, -1
  • String callingPackage, 当前的context.getBasePackageName()
  • Intent intent, intent,即new Intent(MainActivity.this, SecondActivity.class);
  • String resolvedType,
  • IVoiceInteractionSession voiceSession, null
  • IVoiceInteractor voiceInteractor, null
  • IBinder resultTo, mToken 就是在 MainActivity 的 attach 方法里赋值的;
  • String resultWho,mEmbeddedID,这个值是在 MainActivityattach 方法中赋值的。
  • int requestCode,-1
  • int startFlags,0
  • ProfilerInfo profilerInfo,null
  • WaitResult outResult, null
  • Configuration config,null
  • Bundle options,null
  • int userId, useId
  • IActivityContainer iContainer, null
  • TaskRecord inTask,null
	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, int userId, IActivityContainer iContainer, TaskRecord inTask) {
       
        boolean componentSpecified = intent.getComponent() != null;

        // Don't modify the client's object!
        intent = new Intent(intent);

        // Collect information about the target of the Intent.
        // 调用resolveActivity()根据意图intent参数,解析目标Activity的一些信息保存到aInfo中
        ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
                profilerInfo, userId); 

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

            final ActivityStack stack;
            // container 为 null,进入此分支
            if (container == null || container.mStack.isOnHomeDisplay()) {
                // 会在这里赋值
                stack = getFocusedStack();
            } else {
                stack = container.mStack;
            }

            final long origId = Binder.clearCallingIdentity();
	    	// 不会进入这个 if 分支,因为我们没有 <application> 节点设置 android:cantSaveState 属性
            if (aInfo != null &&
                    (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
               ...
            }
	    	// 调用这里
            int res = startActivityLocked(caller, intent, resolvedType, aInfo,
                    voiceSession, voiceInteractor, resultTo, resultWho,
                    requestCode, callingPid, callingUid, callingPackage,
                    realCallingPid, realCallingUid, startFlags, options,
                    componentSpecified, null, container, inTask); 

            return res;
        }
    }

2.5 ActivityStackSupervisor类的startActivityLocked()方法

这个方法的工作包括:检查调用者的权限,检查intent,检查权限,构造待启动 Activity 对应的 ActivityRecord对象。

  • IApplicationThread caller,mMainThread.getApplicationThread()类型转换得到的IApplicationThread对象,ApplicationThreadProxy 对象
  • Intent intent, intent,即new Intent(MainActivity.this, SecondActivity.class);
  • String resolvedType,
  • ActivityInfo aInfo, startActivityMayWait()方法中调用 resolveActivity 得到的 ActivityInfo 对象。
  • IVoiceInteractionSession voiceSession, null
  • IVoiceInteractor voiceInteractor, null
  • IBinder resultTo, mToken
  • String resultWho, mEmbeddedID,这个值是在 Activityattach 方法中赋值的。
  • int requestCode, -1
  • int callingPid, -1
  • int callingUid, -1
  • String callingPackage,当前的context.getBasePackageName()
  • int realCallingPid, Binder.getCallingPid()的值
  • int realCallingUid, Binder.getCallingUid()得值
  • int startFlags, 0
  • Bundle options, null
  • boolean componentSpecified, true
  • ActivityRecord[] outActivity, null
  • ActivityContainer container, getFocusedStack() 的值
  • TaskRecord inTask,null
   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 componentSpecified, ActivityRecord[] outActivity, ActivityContainer container,
            TaskRecord inTask) {
        int err = ActivityManager.START_SUCCESS;

        ProcessRecord callerApp = null;
        if (caller != null) {
            callerApp = mService.getRecordForAppLocked(caller); // 获取调用者的进程记录对象 ProcessRecord 对象
            if (callerApp != null) {
                callingPid = callerApp.pid;
                callingUid = callerApp.info.uid;
            } else {
                Slog.w(TAG, "Unable to find app for caller " + caller
                      + " (pid=" + callingPid + ") when starting: "
                      + intent.toString());
                err = ActivityManager.START_PERMISSION_DENIED; // 找不到调用者,返回权限拒绝的标记.
            }
        }
        ActivityRecord sourceRecord = null;
        ActivityRecord resultRecord = null; // 声明一个结果Activity在栈中的记录
        if (resultTo != null) {
            // 根据resultTo Binder对象得到其指向的ActivityRecord,即MainActivity的ActivityRecord信息
            sourceRecord = isInAnyStackLocked(resultTo); 
        }
       	// 获取结果Activity的任务栈的ActivityStack对象(理解为任务栈的管理者),这里获取的是null.
        ActivityStack resultStack = resultRecord == null ? null : resultRecord.task.stack; 

        final int launchFlags = intent.getFlags();
		// 不会进入这里,因为我没有给intent设置Intent.FLAG_ACTIVITY_FORWARD_RESULT这个标记位
        if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) { 
            ...
        }
		// 不走这个分支,我有组件
        if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) { 
            err = ActivityManager.START_INTENT_NOT_RESOLVED;
            ...
        }
		// 不走, 我有这个SecondActivity类
        if (err == ActivityManager.START_SUCCESS && aInfo == null) { 
            err = ActivityManager.START_CLASS_NOT_FOUND;
            ...
        }
		// 不走, 完全没有使用voice session
        if (err == ActivityManager.START_SUCCESS && sourceRecord != null
                && sourceRecord.task.voiceSession != null) { 
            ...
        }
		// 不走, voiceSession是null
        if (err == ActivityManager.START_SUCCESS && voiceSession != null) { 
           ...
        }
		// 不走, error仍是初始化的值
        if (err != ActivityManager.START_SUCCESS) { 
            ...
            return err;
        }
		// 权限检查,我没有问题,都可以启动SecondActivity了,肯定过了这一关
        final int startAnyPerm = mService.checkPermission(
                START_ANY_ACTIVITY, callingPid, callingUid);
        final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
                callingUid, aInfo.applicationInfo.uid, aInfo.exported);
        if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
            ...
        }
		// abort意思是使流产; 使夭折; 使中止,这个该是false,不然就不用往下走了
		// mIntentFirewall 是 IntentFirewall 对象,是系统的意图防火墙,可以拦截掉要打开的意图
        boolean abort = !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
                callingPid, resolvedType, aInfo.applicationInfo);
        // mService.mController 目前是 null,不会进入此分支
        if (mService.mController != null) {
            try {
                Intent watchIntent = intent.cloneFilter();
                // 判断 ActivityController 是否拦截启动的 Activity,系统级的应用锁可以从这里入手实现
                abort |= !mService.mController.activityStarting(watchIntent,
                        aInfo.applicationInfo.packageName);
            } catch (RemoteException e) {
                mService.mController = null;
            }
        }

        if (abort) { // 不走这里
            ...
            return ActivityManager.START_SUCCESS;
        }
		// 创建一个ActivityRecord对象,用于记录一个 Activity。
        ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
                intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,
                requestCode, componentSpecified, this, container, options);
        if (outActivity != null) { // 这里的outActivity是null的
            outActivity[0] = r;
        }

        final ActivityStack stack = getFocusedStack();
        // 没有切换 app,所以不会进入此分支,参考:https://blog.csdn.net/QQxiaoqiang1573/article/details/77015379
        if (voiceSession == null && (stack.mResumedActivity == null
                || stack.mResumedActivity.info.applicationInfo.uid != callingUid)) {
            ...
        }
        doPendingActivityLaunchesLocked(false);
		// 最后调用这里
        err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
                startFlags, true, options, inTask);
        return err;
    }

2.6 ActivityStackSupervisor类的startActivityUncheckedLocked()方法

这个方法的作用是设置launchFlags

  • ActivityRecord r, 是在 startActivityLocked() 方法中构造出的 ActivityRecord 对象,也就是 SecondActivity 对应的 ActivityRecord 对象
  • ActivityRecord sourceRecord,是 MainActivity 对象的 ActivityReord 对象
  • IVoiceInteractionSession voiceSession, null
  • IVoiceInteractor voiceInteractor, null
  • int startFlags,0
  • boolean doResume, true
  • Bundle options, null
  • TaskRecord inTask,null
    final int startActivityUncheckedLocked(ActivityRecord r, ActivityRecord sourceRecord,
            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags,
            boolean doResume, Bundle options, TaskRecord inTask) {
        final Intent intent = r.intent;
        final int callingUid = r.launchedFromUid;
        
        if (inTask != null && !inTask.inRecents) {
            inTask = null;
        }

        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;

        int launchFlags = intent.getFlags();
       
		// 构造ActivityRecord的options为null,所以r.mLaunchTaskBehind为false,launchTaskBehind为false
        final boolean launchTaskBehind = r.mLaunchTaskBehind
                && !launchSingleTask && !launchSingleInstance
                && (launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0; 
		// 不走这里,因为没有设置 Intent.FLAG_ACTIVITY_NEW_TASK
        if (r.resultTo != null && (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) { 
            ...
        }
		// 不走这个分支,因为没有设置 Intent.FLAG_ACTIVITY_NEW_DOCUMENT
        if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0 && r.resultTo == null) {
            ...
        }
        // 不走这里,因为没有设置 Intent.FLAG_ACTIVITY_NEW_TASK
        if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
            ...
        }

        mUserLeaving = (launchFlags & Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;

        // 本次doResume为true,所以不会进入if语句内部
        if (!doResume) { 
            r.delayedResume = true;
        }

        ActivityRecord notTop =
                (launchFlags & Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP) != 0 ? r : null; // 为 null
        // 不会走这个分支,因为 startFlags 是 0
        if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
            ...
        }

        boolean addingToTask = false;
        TaskRecord reuseTask = null;

        // 当前的sourceRecord不为null, inTask 为 null,不会走这里.
        if (sourceRecord == null && inTask != null && inTask.stack != null) { 
            ...
        } else {
            inTask = null; // 进入这里
        }

        if (inTask == null) {
            if (sourceRecord == null) {
                ...
            } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
                launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
            } else if (launchSingleInstance || launchSingleTask) {
                launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
            }
        }

        ActivityInfo newTaskInfo = null;
        Intent newTaskIntent = null;
        ActivityStack sourceStack;
        if (sourceRecord != null) {
            // sourceRecord 没有 finish,不会进入下面的分支
            if (sourceRecord.finishing) {
                ...
            } else {
            	// 当调用者 ActivityRecord 不为空且不处于 finish 状态时,给 sourceStack 赋值
                sourceStack = sourceRecord.task.stack;
            }
        } else {
            ...
        }

        boolean movedHome = false;
        ActivityStack targetStack;
		// 把前面配置的lauchFlags,设置给intent
        intent.setFlags(launchFlags); 

        // 本次调用没有FLAG_ACTIVITY_NEW_TASK, 不会进入这里
        if (((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
                (launchFlags & Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
                || launchSingleInstance || launchSingleTask) { 
                ...
        }

		// 要启动的Activity的包名不为null,成立,走这里
        if (r.packageName != null) { 
            ActivityStack topStack = getFocusedStack();
            ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(notTop);
            // 不走这里,我启动的是SecondActivity,不是当前的MainActivity
            if (top != null && r.resultTo == null) { 
                if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
                    ...
                }
            }
        } else { // 不会走这里
            ...
        }

        boolean newTask = false;
        boolean keepCurTransition = false;

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

        // 这一段代码主要是为了获取 ActivityStack targetStack 的值。
        // 本次不走这里, inTask 为 null,且没有设置 Intent.FLAG_ACTIVITY_NEW_TASK 这个 Flag
        if (r.resultTo == null && inTask == null && !addingToTask
                && (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) { 
            ...
        } else if (sourceRecord != null) { // 走这里
            final TaskRecord sourceTask = sourceRecord.task;
            targetStack = sourceTask.stack; // 目标的ActivityStack指向来源的ActivityStack
            targetStack.moveToFront();
            final TaskRecord topTask = targetStack.topTask();
            // 一个现存的Activity正在开启这个新的Activity,所以把新的Activity放在和
            // 启动它的那个Activity的同样的任务栈里.这就是我这次要的效果.走这里.
            r.setTask(sourceTask, null);
        } else if (inTask != null) { // 不走这里,第一个if走过了
           ...
        } else {  // 不走这里,第一个if走过了
           ...
        }
        ...   
        ActivityStack.logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
        targetStack.mLastPausedActivity = null;
        // 最后调用这里,调用的是 ActivityStack 类的 startActivityLocked() 方法
        targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options); 
        
        return ActivityManager.START_SUCCESS;
    }

2.7 ActivityStack类的startActivityLocked()方法

这个方法的作用是把待启动的 Activity 对应的 ActivityRecord 对象入栈。

  • ActivityRecord r, 是在 ActivityStackSupervisor 的startActivityLocked() 方法中构造出的 ActivityRecord 对象,也就是 SecondActivity 对应的 ActivityRecord 对象
  • boolean newTask, false
  • boolean doResume, true
  • boolean keepCurTransition, false
  • Bundle options,null
    final void startActivityLocked(ActivityRecord r, boolean newTask,
            boolean doResume, boolean keepCurTransition, Bundle options) {
        TaskRecord rTask = r.task;
        final int taskId = rTask.taskId;
      
        TaskRecord task = null;
        if (!newTask) { // 进入这里,找到 task。
            // If starting in an existing task, find where that is... 需要启动一个现存的栈,找到它的位置
            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) { // 找到了我要的那个任务栈
                    break;
                } 
            }
        }

        task = r.task;
        
        task.addActivityToTop(r); // 将SecondActivity对应的ActivityRecord对象插入栈顶
        task.setFrontOfTask(); // 标记任务栈的顶层ActivityRecord

        r.putInHistory(); // 标记ActivityRecord已经放置到宿主栈中
        if (!isHomeStack() || numActivities() > 0) { // 进入此分支
            
            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_ON_LOCK_SCREEN) != 0, r.userId,
                    r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind);
            boolean doShow = true;
            if (newTask) { // false
                ...
            } 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 {
            ...
        }

        if (doResume) { //doResume为true, 进入这里
            mStackSupervisor.resumeTopActivitiesLocked(this, r, options); // 最后调用这里
        }
    }

2.8 ActivityStackSupervisor类的resumeTopActivitiesLocked()

这个方法的作用是:确保目标的 ActivityStack 处于前台。

  • ActivityStack targetStack, ActivityStack 对象
  • ActivityRecord target, 是在 ActivityStackSupervisor 的startActivityLocked() 方法中构造出的 ActivityRecord 对象,也就是 SecondActivity 对应的 ActivityRecord 对象
  • Bundle targetOptions,null
    boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
            Bundle targetOptions) {
        if (targetStack == null) {
            targetStack = getFocusedStack();
        }
        // Do targetStack first.
        boolean result = false;
        if (isFrontStack(targetStack)) { // 返回true,在之前通过task.setFrontOfTask()设置为顶层
            result = targetStack.resumeTopActivityLocked(target, targetOptions); // 调用这里
        }
        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
                final ActivityStack stack = stacks.get(stackNdx);
                if (stack == targetStack) {
                    // Already started above. 上面刚已经启动了
                    continue;
                }
                if (isFrontStack(stack)) {
                    stack.resumeTopActivityLocked(null);
                }
            }
        }
        return result;
    }

2.9 ActivityStack类的resumeTopActivityLocked()方法

主要实现对 resumeTopActivityInnerLocked 方法调用的控制,保证每次只有一个Activity执行resumeTopActivityLocked()操作.。

  • ActivityRecord prev, 是在 ActivityStackSupervisor 的startActivityLocked() 方法中构造出的 ActivityRecord 对象,也就是 SecondActivity 对应的 ActivityRecord 对象
  • Bundle options, null
    final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
        if (inResumeTopActivity) { // 这个标记是为了防止多次调用resumeTopActivityInnerLocked
            // Don't even start recursing. 防止递归调用
            return false;
        }

        boolean result = false;
        try {
            // Protect against recursion.
            inResumeTopActivity = true;
            result = resumeTopActivityInnerLocked(prev, options); // 调用这里
        } finally {
            inResumeTopActivity = false;
        }
        return result;
    }

2.10 ActivityStack类的resumeTopActivityInnerLocked()方法

  • ActivityRecord prev, 是在 ActivityStackSupervisor 的startActivityLocked() 方法中构造出的 ActivityRecord 对象,也就是 SecondActivity 对应的 ActivityRecord 对象;
  • Bundle options, null
    final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
        // 系统还没有进入 booting 或 booted 状态,则不允许启动 Activity
        if (!mService.mBooting && !mService.mBooted) {
            // Not ready yet! 还没有准备好
            return false;
        }
        // 这里没有设置 parentActivity,所以不会进入如下分支
        ActivityRecord parent = mActivityContainer.mParentActivity;
        if ((parent != null && parent.state != ActivityState.RESUMED) ||
                !mActivityContainer.isAttachedLocked()) {
            // Do not resume this stack if its parent is not resumed.
            // TODO: If in a loop, make sure that parent stack resumeTopActivity is called 1st.
            return false;
        }
         
        cancelInitializingActivities();

        // Find the first activity that is not finishing. 
        // 找到第一个没有finishing的栈顶 Activity,即 SecondActivity
        ActivityRecord next = topRunningActivityLocked(null);

        // Remember how we'll process this pause/resume situation, and ensure
        // that the state is reset however we wind up proceeding.
        // 记住我们怎样处理这个暂停/恢复的情形,并且确保不管我们怎样结束继续处理,状态都可以被重置。
        final boolean userLeaving = mStackSupervisor.mUserLeaving;
        mStackSupervisor.mUserLeaving = false;
        // SecondActivity 对应的 ActivityRecord 对象所处的任务栈 TaskRecord 对象
        final TaskRecord prevTask = prev != null ? prev.task : null;
        // 不走这里, next 不是 null。
        if (next == null) {
           ...
        }

        next.delayedResume = false;

        // If the top activity is the resumed one, nothing to do.
        // 不走这里,顶层的页面是新的页面 mResumedActivity 是 MainActivity,next 是 SecondActivity。
        if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
                    mStackSupervisor.allResumedActivitiesComplete()) {
           ...
        }

        final TaskRecord nextTask = next.task;
        // prevTask.isOverHomeStack() 为 false,所以不会进入此分支
        if (prevTask != null && prevTask.stack == this &&
                prevTask.isOverHomeStack() && prev.finishing && prev.frontOfTask) {
            ...
        }

        // If we are sleeping, and there is no resumed activity, and the top
        // activity is paused, well that is the state we want.
        // 处于睡眠或者关机状态,top activity 已经暂停的情况下,本次分析不会进入此分支
        if (mService.isSleepingOrShuttingDown()
                && mLastPausedActivity == next
                && mStackSupervisor.allPausedActivitiesComplete()) {
           ...
        }

        // Make sure that the user who owns this activity is started.  If not,
        // we will just leave it as is because someone should be bringing
        // another user's activities to the top of the stack.
        // 拥有该 activity 的用户没有启动则直接返回,本次不会进入此分支
        if (mService.mStartedUsers.get(next.userId) == null) {
            return false;
        }

        // The activity may be waiting for stop, but that is no longer
        // appropriate for it.
        // Activity 或许正在等待停止,但是对它来说那样做已经不再合适了。
        mStackSupervisor.mStoppingActivities.remove(next);
        mStackSupervisor.mGoingToSleepActivities.remove(next);
        next.sleeping = false;
        mStackSupervisor.mWaitingVisibleActivities.remove(next);

        if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);

        // If we are currently pausing an activity, then don't do anything
        // until that is done.
        // 如果我们正在暂停一个 activity,那么就直接返回。本次分析,不会进入此分支。
        if (!mStackSupervisor.allPausedActivitiesComplete()) {
            return false;
        }

        // We need to start pausing the current activity so the top one
        // can be resumed...等待暂停当前的 activity 完成,再 resume top activity
        // Activity 的启动参数中包含 FLAG_RESUME_WHILE_PAUSING
        // 表示可以在当前显示的Activity执行Pausing时,同时进行Resume操作
        // dontWaitForPause 为 true,则表示不需要等待当前 Activity 执行完 pause,顶层的 activity 就可以 resume
        boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
        // 暂停所有处于后台栈的 activity
        boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
        // 将前台 ActivityStack 正在显示的 Activity 迁移到 pausing 状态
        if (mResumedActivity != null) {
            // 当前 resumed 状态的 activity 不为 null,则需要先暂停该 activity
            // 本次分析情况下,就是暂停 MainActivity。
            pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
            if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Pausing " + mResumedActivity);
        }
        // 当前有正在 pausing 的 Activity,pausing 为true,所以进入此分支
        if (pausing) {
            // 更新 lru 列表
            if (next.app != null && next.app.thread != null) {
                mService.updateLruProcessLocked(next.app, true, null);
            }
            // 注意:本次分析这里返回了,所以不用往下看了。
            return true;
        }
        // 省略了很多代码
        ...
    }

2.11 ActivityStack类的startPausingLocked()方法

  • boolean userLeaving false,
  • boolean uiSleeping false,
  • boolean resuming true,
  • boolean dontWait false.
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming,
        boolean dontWait) {
    // mPausingActivity 目前还是 null
    if (mPausingActivity != null) {
        Slog.wtf(TAG, "Going to pause when pause is already pending for " + mPausingActivity);
        completePauseLocked(false);
    }
    // mResumedActivity 的值是 MainActivity 对应的 ActivityRecord 对象,不是 null
    ActivityRecord prev = mResumedActivity;
    if (prev == null) { // 不会进入此分支
        ...
    }
    if (mActivityContainer.mParentActivity == null) {
        // Top level stack, not a child. Look for child stacks.
		// 暂停所有子栈的 activity
        mStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping, resuming, dontWait);
    }
    // 清空 mResumedActivity 的值
    mResumedActivity = null;
    // 把当前处于 resumed 状态的 MainActivity 对应的 ActivityRecord 赋值给 mPausingActivity 和 mLastPausedActivity
    mPausingActivity = prev;
    mLastPausedActivity = prev;
    
    prev.state = ActivityState.PAUSING;
    prev.task.touchActiveTime();
    clearLaunchTime(prev);
    // 找到第一个没有finishing的栈顶 Activity,即 SecondActivity 对应的 ActivityRecord 对象
    final ActivityRecord next = mStackSupervisor.topRunningActivityLocked();
    ...
    // prev 是 ActivityRecord 对象,对应着 MainActivity
    // prev.app 是 ProcessRecord 对象
    // prev.app.thread 是 IApplicationThread 对象,用于 system_server 服务端进程和客户端进程进行通讯
    if (prev.app != null && prev.app.thread != null) {
        try {
           
            mService.updateUsageStats(prev, false);
            prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
                    userLeaving, prev.configChangeFlags, dontWait);
        } catch (Exception e) {
            ...
        }
    } else {
        ...
    }
    
    // mPausingActivity 不为 null,会进入 if 分支
    if (mPausingActivity != null) {
        ...
        if (dontWait) {
            ...
        } else { // dontWait 为false,所以进入else分支
            // 如果在 500ms 内没有收到 app 的响应,就再执行该方法。
            Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
            msg.obj = prev;
            prev.pauseTime = SystemClock.uptimeMillis();
            mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
            return true;
        }
    } else {
        ...
    }
}

prev.app.thread 实际上是一个ApplicationThreadProxy对象。

2.12 ApplicationThreadProxy的schedulePauseActivity()方法

  • IBinder token MainActivity 的 token,
  • boolean finished false,
  • boolean userLeaving false,
  • int configChanges,
  • boolean dontReport false
class ApplicationThreadProxy implements IApplicationThread {
    private final IBinder mRemote;
    
    public ApplicationThreadProxy(IBinder remote) {
        mRemote = remote;
    }
    
    public final IBinder asBinder() {
        return mRemote;
    }
    
    public final void schedulePauseActivity(IBinder token, boolean finished,
            boolean userLeaving, int configChanges, boolean dontReport) throws RemoteException {
        Parcel data = Parcel.obtain();
        data.writeInterfaceToken(IApplicationThread.descriptor);
        data.writeStrongBinder(token);
        data.writeInt(finished ? 1 : 0);
        data.writeInt(userLeaving ? 1 :0);
        data.writeInt(configChanges);
        data.writeInt(dontReport ? 1 : 0);
        mRemote.transact(SCHEDULE_PAUSE_ACTIVITY_TRANSACTION, data, null,
                IBinder.FLAG_ONEWAY);
        data.recycle();
    }
    ...
}

2.13 ApplicationThreadNative的onTransact方法

public abstract class ApplicationThreadNative extends Binder
        implements IApplicationThread {

    static public IApplicationThread asInterface(IBinder obj) {
        if (obj == null) {
            return null;
        }
        IApplicationThread in =
            (IApplicationThread)obj.queryLocalInterface(descriptor);
        if (in != null) {
            return in;
        }
        
        return new ApplicationThreadProxy(obj);
    }
    
    public ApplicationThreadNative() {
        attachInterface(this, descriptor);
    }
    
    @Override
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
            throws RemoteException {
        switch (code) {
        case SCHEDULE_PAUSE_ACTIVITY_TRANSACTION:
        {
            data.enforceInterface(IApplicationThread.descriptor);
            IBinder b = data.readStrongBinder();
            boolean finished = data.readInt() != 0;
            boolean userLeaving = data.readInt() != 0;
            int configChanges = data.readInt();
            boolean dontReport = data.readInt() != 0;
            schedulePauseActivity(b, finished, userLeaving, configChanges, dontReport);
            return true;
        }

	...
        }

        return super.onTransact(code, data, reply, flags);
    }

    public IBinder asBinder()
    {
        return this;
    }
}

2.14 ApplicationThread类的schedulePauseActivity()方法

  • IBinder token MainActivity 的 token,
  • boolean finished false,
  • boolean userLeaving false,
  • int configChanges,
  • boolean dontReport false
public final class ActivityThread {
    final H mH = new H();
    final ApplicationThread mAppThread = new ApplicationThread();

    private class ApplicationThread extends ApplicationThreadNative {

        public final void schedulePauseActivity(IBinder token, boolean finished,
                boolean userLeaving, int configChanges, boolean dontReport) {
            sendMessage(
                    // finished 为 false,所以取H.PAUSE_ACTIVITY
                    finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
                    token, // obj 为 token
                    (userLeaving ? 1 : 0) | (dontReport ? 2 : 0), // arg1 为 0
                    configChanges); // args 为 configChanges
        }

    }

    private void sendMessage(int what, Object obj) {
        sendMessage(what, obj, 0, 0, false);
    }

    private void sendMessage(int what, Object obj, int arg1) {
        sendMessage(what, obj, arg1, 0, false);
    }

    private void sendMessage(int what, Object obj, int arg1, int arg2) {
        sendMessage(what, obj, arg1, arg2, false);
    }

    private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
    
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            msg.setAsynchronous(true);
        }
        mH.sendMessage(msg);
    }
}

2.15 H类的handleMessage()方法

public final class ActivityThread {
	final H mH = new H();
	
    private class H extends Handler {
        public static final int PAUSE_ACTIVITY          = 101;
		
        public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
		...
                case PAUSE_ACTIVITY:
                    handlePauseActivity((IBinder)msg.obj, false, (msg.arg1&1) != 0, msg.arg2,
                            (msg.arg1&2) != 0);
                    maybeSnapshot();
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                    break;
               ...
            }
        } 
    }
}

2.16 ActivityThread类的handlePauseActivity()方法

  • IBinder token MainActivity 的 token,
  • boolean finished false,
  • boolean userLeaving false,
  • int configChanges,
  • boolean dontReport false
private void handlePauseActivity(IBinder token, boolean finished,
        boolean userLeaving, int configChanges, boolean dontReport) {
    ActivityClientRecord r = mActivities.get(token);
    if (r != null) {
        //Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
        if (userLeaving) {
            performUserLeavingActivity(r);
        }
        r.activity.mConfigChangeFlags |= configChanges;
       
        performPauseActivity(token, finished, r.isPreHoneycomb());
      
        // Tell the activity manager we have paused. 告诉 AMS 我们已经暂停了。
        if (!dontReport) { // dontReport 为false,所以会进入此分支
            try {
                ActivityManagerNative.getDefault().activityPaused(token);
            } catch (RemoteException ex) {
            }
        }
        mSomeActivitiesChanged = true;
    }
}

2.16.1 ActivityThread类的performPauseActivity()方法

  • IBinder token MainActivity 的 token,
  • boolean finished false,
  • boolean saveState false
final Bundle performPauseActivity(IBinder token, boolean finished,
        boolean saveState) {
    ActivityClientRecord r = mActivities.get(token);
    return r != null ? performPauseActivity(r, finished, saveState) : null;
}
final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
        boolean saveState) {
    if (r.paused) { // 不会进入此分支
        ...
    }
    
    try {
        // Next have the activity save its current state and managed dialogs...
        if (!r.activity.mFinished && saveState) {
            callCallActivityOnSaveInstanceState(r);
        }
        // Now we are idle.
        r.activity.mCalled = false;
        // 通过 Instrumentation 对象回调 Activity 的 onPause 方法
        mInstrumentation.callActivityOnPause(r.activity);
        
    } catch (SuperNotCalledException e) {
        throw e;
    } catch (Exception e) {
        
    }
    r.paused = true;
    // Notify any outstanding on paused listeners
    ArrayList<OnActivityPausedListener> listeners;
    synchronized (mOnPauseListeners) {
        listeners = mOnPauseListeners.remove(r.activity);
    }
    int size = (listeners != null ? listeners.size() : 0);
    for (int i = 0; i < size; i++) {
        listeners.get(i).onPaused(r.activity);
    }
    return !r.activity.mFinished && saveState ? r.state : null;
}

2.17 ActivityManagerService的activityPaused()方法

  • IBinder token MainActivity 的 token,
@Override
public final void activityPaused(IBinder token) {
    final long origId = Binder.clearCallingIdentity();
    synchronized(this) {
        // 根据 token 查找所属的 ActivityStack 对象
        ActivityStack stack = ActivityRecord.getStackLocked(token);
        if (stack != null) {
            stack.activityPausedLocked(token, false);
        }
    }
    Binder.restoreCallingIdentity(origId);
}

2.18 ActivityStack类的activityPausedLocked()方法

  • IBinder token MainActivity 的 token,
  • boolean timeout false.
final void activityPausedLocked(IBinder token, boolean timeout) {
    // 根据 token,获取 ActivityRecord 对象,即 MainActivity 对应的 ActivityRecord 对象。
    final ActivityRecord r = isInStackLocked(token);
    if (r != null) {
        mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
        if (mPausingActivity == r) { // 进入此分支
            completePauseLocked(true);
        } else {
            ...
        }
    }
}

2.19 ActivityStack类的completePauseLocked()方法

  • boolean resumeNext true
private void completePauseLocked(boolean resumeNext) {
    // mPausingActivity 即 MainActivity 对应的 ActivityRecord 对象。
    ActivityRecord prev = mPausingActivity;
    if (prev != null) {
        prev.state = ActivityState.PAUSED;
        ...
        mPausingActivity = null;
    }
    if (resumeNext) {
        final ActivityStack topStack = mStackSupervisor.getFocusedStack();
        if (!mService.isSleepingOrShuttingDown()) { // 进入此分支
            mStackSupervisor.resumeTopActivitiesLocked(topStack, prev, null);
        } else {
            ...
        }
    }
    ...
}

2.20 ActivityStackSupervisor类的resumeTopActivitiesLocked()方法

  • ActivityStack targetStack, ActivityStack 对象
  • ActivityRecord target, 是 MainActivity 对应的 ActivityRecord 对象
  • Bundle targetOptions,null
boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
        Bundle targetOptions) {
    if (targetStack == null) {
        targetStack = getFocusedStack();
    }
    // Do targetStack first.
    boolean result = false;
    if (isFrontStack(targetStack)) {
        // 调用到这里
        result = targetStack.resumeTopActivityLocked(target, targetOptions);
    }
    for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
        final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
        for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
            final ActivityStack stack = stacks.get(stackNdx);
            if (stack == targetStack) {
                // Already started above.
                continue;
            }
            if (isFrontStack(stack)) {
                stack.resumeTopActivityLocked(null);
            }
        }
    }
    return result;
}

2.21 ActivityStack类的resumeTopActivityLocked()方法

主要实现对 resumeTopActivityInnerLocked 方法调用的控制,保证每次只有一个Activity执行resumeTopActivityLocked()操作.。

  • ActivityRecord prev, 是 MainActivity 对应的 ActivityRecord 对象
  • Bundle options, null
final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
    if (inResumeTopActivity) {
        // Don't even start recursing.
        return false;
    }
    boolean result = false;
    try {
        // Protect against recursion.
        inResumeTopActivity = true;
        // 调用到这里
        result = resumeTopActivityInnerLocked(prev, options);
    } finally {
        inResumeTopActivity = false;
    }
    return result;
}

2.22 ActivityStack类的resumeTopActivityInnerLocked()方法

  • ActivityRecord prev, 是 MainActivity 对应的 ActivityRecord 对象
  • Bundle options, null
final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
   
    // Find the first activity that is not finishing.
    // next 为 SecondActivity 对应的 ActivityRecord 对象
    ActivityRecord next = topRunningActivityLocked(null);
   
    final TaskRecord prevTask = prev != null ? prev.task : null;
    
    next.delayedResume = false;
    // mResumedActivity 为 null
    if (mResumedActivity == next && next.state == ActivityState.RESUMED &&
                mStackSupervisor.allResumedActivitiesComplete()) {
       ...
    }
    final TaskRecord nextTask = next.task;
  
    
    // The activity may be waiting for stop, but that is no longer
    // appropriate for it.
    mStackSupervisor.mStoppingActivities.remove(next);
    mStackSupervisor.mGoingToSleepActivities.remove(next);
    next.sleeping = false;
    mStackSupervisor.mWaitingVisibleActivities.remove(next);
    
    // We need to start pausing the current activity so the top one
    // can be resumed...
    boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;
    boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause);
    if (mResumedActivity != null) { // mResumedActivity 为 null,不会进入此分支
        pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
    }
    if (pausing) { // pausing 为 false
        ...
    }

    if (mService.isSleeping() && mLastNoHistoryActivity != null &&
            !mLastNoHistoryActivity.finishing) {
       ...
    }
    // prev, 是 MainActivity 对应的 ActivityRecord 对象
    // next 为 SecondActivity 对应的 ActivityRecord 对象,所以进入if分支
    if (prev != null && prev != next) {
        ... 省略不关键的代码
    }
   
    // We are starting up the next activity, so tell the window manager
    // that the previous one will be hidden soon.  This way it can know
    // to ignore it when computing the desired screen orientation.
    // 我们在开启下一个 activity,所以告诉 wms 上一个 activity 将会被隐藏了。
    boolean anim = true;
    if (prev != null) {
        if (prev.finishing) {
            ...
        } else { // 进入此分支
            ...省略不关键的代码
        }
       
    } else {
        ...
    }
    ...
    ActivityStack lastStack = mStackSupervisor.getLastStack();
    // next.app 目前为 null,所以不会进入 if 分支
    if (next.app != null && next.app.thread != null) {
      ...
    } else { // 进入 else 分支了
        if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: Restarting " + next);
        // 最终调用到这里
        mStackSupervisor.startSpecificActivityLocked(next, true, true);
    }
    return true;
}

2.23 ActivityStatckSupervisor类的startSpecificActivityLocked()方法

  • ActivityRecord r,是在 ActivityStackSupervisor 的startActivityLocked() 方法中构造出的 ActivityRecord 对象,也就是 SecondActivity 对应的 ActivityRecord 对象
  • boolean andResume, true
  • boolean checkConfig,true
    void startSpecificActivityLocked(ActivityRecord r,
            boolean andResume, boolean checkConfig) {
        // Is this activity's application already running?
        // 判断页面的应用是否已经在运行了,这里会返回 true
        ProcessRecord app = mService.getProcessRecordLocked(r.processName,
                r.info.applicationInfo.uid, true);

        r.task.stack.setLaunchTime(r);

        if (app != null && app.thread != null) {
            try {
                // 调用这里,真正启动Activity
                realStartActivityLocked(r, app, andResume, checkConfig); 
                return;
            } catch (RemoteException e) {
            }
        }
    }

2.24 ActivityStatckSupervisor类的realStartActivityLocked()方法

  • ActivityRecord r,是在 ActivityStackSupervisor 的startActivityLocked() 方法中构造出的 ActivityRecord 对象,也就是 SecondActivity 对应的 ActivityRecord 对象
  • ProcessRecord app, ProcessRecord 对象
  • boolean andResume, true
  • boolean checkConfig,true
    final boolean realStartActivityLocked(ActivityRecord r,
            ProcessRecord app, boolean andResume, boolean checkConfig)
            throws RemoteException {
        // 把 ProcessRecord 对象赋值给 ActivityRecord 的 ProcessRecord app 成员变量。
        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);
        }

        final ActivityStack stack = r.task.stack;
        try {
            if (app.thread == null) {
                throw new RemoteException();
            }
            // 调用这里,计划启动Activity了
            app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                    System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
                    r.compat, r.task.voiceInteractor, app.repProcState, r.icicle, r.persistentState,
                    results, newIntents, !andResume, mService.isNextTransitionForward(),
                    profilerInfo); 
        } catch (RemoteException e) {
           ...
        }

        r.launchFailed = false;
       
        if (andResume) {
            // As part of the process of launching, ActivityThread also performs
            // a resume. 更新 resumed 状态的 activity 信息
            stack.minimalResumeActivityLocked(r);
        } else {
            ...
        }

        return true;
    }

这里的app.thread是一个IApplicationThread对象,这里又是一个Binder的使用.IApplicationThread继承于IInterface,它代表了远程Service有什么能力,ApplicationThreadNative指的是Binder本地对象,是个抽象类,它的实现是ApplicationThread,它的位置是在ActivityThread.java中,是ActivityThread类的一个内部类.真正的执行操作是在ApplicationThread中.

2.25 ApplicationThread类的scheduleLaunchActivity()方法

Intent intent,
IBinder token,
int ident,
ActivityInfo info,
Configuration curConfig,
CompatibilityInfo compatInfo,
IVoiceInteractor voiceInteractor,
int procState,
Bundle state,
PersistableBundle persistentState,
List pendingResults,
List pendingNewIntents,
boolean notResumed, false
boolean isForward,
ProfilerInfo profilerInfo,

ApplicationThread 是 ActivityThread 的内部类。

	// we use token to identify this activity without having to send the
        // activity itself back to the activity manager. (matters more with ipc)
        public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
                ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
                IVoiceInteractor voiceInteractor, int procState, Bundle state,
                PersistableBundle persistentState, List<ResultInfo> pendingResults,
                List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
                ProfilerInfo profilerInfo) {

            updateProcessState(procState, false);

            ActivityClientRecord r = new ActivityClientRecord();

            r.token = token;
            r.ident = ident;
            r.intent = intent;
            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;

            updatePendingConfiguration(curConfig);

            sendMessage(H.LAUNCH_ACTIVITY, r); // 调用这里,发送启动Activity的消息
        }

然后调用

    private void sendMessage(int what, Object obj) {
        sendMessage(what, obj, 0, 0, false);
    }

然后调用

	private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
        if (DEBUG_MESSAGES) Slog.v(
            TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
            + ": " + arg1 + " / " + obj);
        Message msg = Message.obtain();
        msg.what = what;
        msg.obj = obj;
        msg.arg1 = arg1;
        msg.arg2 = arg2;
        if (async) {
            msg.setAsynchronous(true);
        }
        mH.sendMessage(msg);
    }

这里mH是一个H对象,H类继承于Handler类,看处理消息的方法:

	public void handleMessage(Message msg) {
            if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
            switch (msg.what) {
                case LAUNCH_ACTIVITY: {
                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
                    final ActivityClientRecord r = (ActivityClientRecord) msg.obj;

                    r.packageInfo = getPackageInfoNoCheck(
                            r.activityInfo.applicationInfo, r.compatInfo);
                    handleLaunchActivity(r, null);
                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
                } break;
               	// 省略了与分析无关的分支
            }
            if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
        }

接着调用handleLaunchActivity,看名字,处理启动Activity,越来越接近终点了

    private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // If we are getting ready to gc after going to the background, well
        // we are back active so skip it.
        unscheduleGcIdler();
        mSomeActivitiesChanged = true;

        if (r.profilerInfo != null) {
            mProfiler.setProfiler(r.profilerInfo);
            mProfiler.startProfiling();
        }

        // Make sure we are running with the most recent config.
        handleConfigurationChanged(null, null);

        if (localLOGV) Slog.v(
            TAG, "Handling launch of " + r);

        Activity a = performLaunchActivity(r, customIntent); // 执行启动Activity,这里Activity被创建出来,其onCreate()和onStart()也会被调用

        if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            Bundle oldState = r.state;
            // 这里新Activity的onResume()会被调用
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed);

            if (!r.activity.mFinished && r.startsNotResumed) {
                try {
                    r.activity.mCalled = false;
                    mInstrumentation.callActivityOnPause(r.activity);
                    if (r.isPreHoneycomb()) {
                        r.state = oldState;
                    }
                    if (!r.activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onPause()");
                    }

                } catch (SuperNotCalledException e) {
                    throw e;

                } catch (Exception e) {
                    if (!mInstrumentation.onException(r.activity, e)) {
                        throw new RuntimeException(
                                "Unable to pause activity "
                                + r.intent.getComponent().toShortString()
                                + ": " + e.toString(), e);
                    }
                }
                r.paused = true;
            }
        } else {
            // If there was an error, for any reason, tell the activity
            // manager to stop us.
            try {
                ActivityManagerNative.getDefault()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
            } catch (RemoteException ex) {
                // Ignore
            }
        }
    }

接着看performLaunchActivity方法

		private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");

        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();
            // Instrumentation使用反射创建了Activity的实例
            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) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to instantiate activity " + component
                    + ": " + e.toString(), e);
            }
        }

        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);

            if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
            if (localLOGV) Slog.v(
                    TAG, r + ": app=" + app
                    + ", appName=" + app.getPackageName()
                    + ", pkg=" + r.packageInfo.getPackageName()
                    + ", comp=" + r.intent.getComponent().toShortString()
                    + ", dir=" + r.packageInfo.getAppDir());

            if (activity != null) {
                Context appContext = createBaseContextForActivity(r, activity);
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
                        + r.activityInfo.name + " with config " + config);
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        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;
                // 这里Activity的onCreate会被调用
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                if (!activity.mCalled) {
                    throw new SuperNotCalledException(
                        "Activity " + r.intent.getComponent().toShortString() +
                        " did not call through to super.onCreate()");
                }
                r.activity = activity;
                r.stopped = true;
                if (!r.activity.mFinished) {
	                // 这里Activity的onStart()会被调用
                    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);
                    }
                    if (!activity.mCalled) {
                        throw new SuperNotCalledException(
                            "Activity " + r.intent.getComponent().toShortString() +
                            " did not call through to super.onPostCreate()");
                    }
                }
            }
            r.paused = true;

            mActivities.put(r.token, r);

        } catch (SuperNotCalledException e) {
            throw e;

        } catch (Exception e) {
            if (!mInstrumentation.onException(activity, e)) {
                throw new RuntimeException(
                    "Unable to start activity " + component
                    + ": " + e.toString(), e);
            }
        }

        return activity;
    }

3. 最后

最后,使用自己的语言把 Activity 的启动流程描述一下:

ActivitystartActivity 方法开始,经过 InstrumentationexecStartActivity,通过 AMP 发起 startActivity 的 binder 跨进程调用,进入到 system_server 进程的 AMSstartActivity 方法中。

在 AMS 中,ASSstartActivityMayWait 方法中负责解析清单文件中的 activity 信息,如果有多个 activity 可选,由用户来选择;ASSstartActivityLocked 方法负责检查要启动的 activity 的信息(是否存在组件,调用方是否有权限),是否要拦截启动,创建目标 activity 的 ActivityRecord 对象;ASSstartActivityUncheckedLocked 方法负责对 launchFlags 进行一些处理,找到目标的 ActivityStack 对象;通过 ActivityStackstartActivityLocked 方法把目标的 ActivityRecord 对象入栈;通过 ASSresumeTopActivitiesLocked 获取前台的 ActivityStack;调用 ActivityStackresumeTopActivityLocked 以及 resumeTopActivityInnerLocked 方法来使栈顶的 activity 进入前台,但是要先通过 ActivityStackstartPausingLocked 方法来使当前正处于 resumed 状态的 activity 暂停,会通过 ATPschedulePauseActivity 方法发起 binder 跨进程调用,进入到应用进程的 ApplicationThreadschedulePauseActivity 方法(该方法运行在客户端的 binder 线程池里面),再经过 mH 将数据切换到应用进程的主进程中执行,由 ActivityThreadhandlePauseActivity 方法处理,再经过 performPauseActivity 内部调用 InstrumentationcallActivityOnPause 方法,内部会调用 ActivityperformPause 方法,会回调 MainActivityonPause 方法。

这之后,会在客户端进程中,通过 AMPactivityPaused 方法发起 binder 跨进程调用,进入到 system_server 进程的 AMSactivityPaused 方法中,内部会调用 ActivityStackactivityPausedLocked 方法,completePauseLocked 方法,再调用 ASSresumeTopActivitiesLocked 方法,内部又会调用 ActivityStackresumeTopActivityLocked 方法,resumeTopActivityInnerLocked 方法,再调用 ASSstartSpecificActivityLocked 方法,realStartActivityLocked 方法真正去开启目标 activity,通过 ATPscheduleLaunchActivity 方法发起 binder 跨进程调用,进入到应用进程的 ApplicationThreadscheduleLaunchActivity 方法(该方法运行在客户端的 binder 线程池里面),经过 mH 将数据切换到应用进程的主进程中去处理,由 ActivityThreadhandleLaunchActivity 来处理,内部会依次调用 performLaunchActivity 方法和 handleResumeActivity 方法。其中,performLaunchActivity 方法内部会通过反射创建目标 activity 的对象,调用其 attach 方法,回调其 onCreate 方法。

参考

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

willwaywang6

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

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

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

打赏作者

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

抵扣说明:

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

余额充值