2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > Android筑基——Activity的启动过程之同进程在一个Activity中启动另一个Activity(基于api21)

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

时间:2024-04-23 01:37:23

相关推荐

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

目录

1. 前言2. 正文2.1 Activity类的startActivity()方法2.2 Instrumentation类的execStartActivity()方法2.3 ActivityManagerService类的startActivity()方法2.4 ActivityStackSupervisor类的startActivityMayWait()方法2.5 ActivityStackSupervisor类的startActivityLocked()方法2.6 ActivityStackSupervisor类的startActivityUncheckedLocked()方法2.7 ActivityStack类的startActivityLocked()方法2.8 ActivityStackSupervisor类的resumeTopActivitiesLocked()2.9 ActivityStack类的resumeTopActivityLocked()方法2.10 ActivityStack类的resumeTopActivityInnerLocked()方法2.11 ActivityStack类的startPausingLocked()方法2.12 ApplicationThreadProxy的schedulePauseActivity()方法2.13 ApplicationThreadNative的onTransact方法2.14 ApplicationThread类的schedulePauseActivity()方法2.15 H类的handleMessage()方法2.16 ActivityThread类的handlePauseActivity()方法2.16.1 ActivityThread类的performPauseActivity()方法 2.17 ActivityManagerService的activityPaused()方法2.18 ActivityStack类的activityPausedLocked()方法2.19 ActivityStack类的completePauseLocked()方法2.20 ActivityStackSupervisor类的resumeTopActivitiesLocked()方法2.21 ActivityStack类的resumeTopActivityLocked()方法2.22 ActivityStack类的resumeTopActivityInnerLocked()方法2.23 ActivityStatckSupervisor类的startSpecificActivityLocked()方法2.24 ActivityStatckSupervisor类的realStartActivityLocked()方法2.25 ApplicationThread类的scheduleLaunchActivity()方法 3. 最后参考

1. 前言

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

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

Activity 启动过程时序图如下:

2. 正文

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

2.1 Activity类的startActivity()方法

startActivity()的方法有两种:

第一种方式是在Activity中直接调用的startActivity()方法,代码为MainActivity.this.startActivity(intent),这种方式会直接调用Activity类中的startActivity()方法,

@Overridepublic void startActivity(Intent intent) {this.startActivity(intent, null);

然后调用了

@Overridepublic 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()方法:

@Overridepublic void startActivity(Intent intent) {mBase.startActivity(intent);}

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

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

然后调用了

@Overridepublic 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,发起启动的ActivityIntent 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发请求,来启动Activityint 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 nameIBinder 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 typeIBinder resultTo = mTokenString resultWho = mEmbeddedID,这个值是在Activityattach方法中赋值的。int requestCode = -1int startFlags = 0ProfilerInfo profilerInfo = nullBundle options = null

@Overridepublic 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, mTokenString resultWho, mEmbeddedID,这个值是在Activityattach方法中赋值的。int requestCode, -1int startFlags, 0ProfilerInfo profilerInfo, nullBundle options, nullint userId, UserHandle.getCallingUserId()

/** Run all ActivityStacks through this */ActivityStackSupervisor mStackSupervisor;@Overridepublic 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, -1String callingPackage, 当前的context.getBasePackageName()Intent intent, intent,即new Intent(MainActivity.this, SecondActivity.class);String resolvedType,IVoiceInteractionSession voiceSession, nullIVoiceInteractor voiceInteractor, nullIBinder resultTo, mToken 就是在 MainActivity 的 attach 方法里赋值的;String resultWho,mEmbeddedID,这个值是在MainActivityattach方法中赋值的。int requestCode,-1int startFlags,0ProfilerInfo profilerInfo,nullWaitResult outResult, nullConfiguration config,nullBundle options,nullint userId, useIdIActivityContainer iContainer, nullTaskRecord 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, nullIVoiceInteractor voiceInteractor, nullIBinder resultTo, mTokenString resultWho, mEmbeddedID,这个值是在Activityattach方法中赋值的。int requestCode, -1int callingPid, -1int callingUid, -1String callingPackage,当前的context.getBasePackageName()int realCallingPid, Binder.getCallingPid()的值int realCallingUid, Binder.getCallingUid()得值int startFlags, 0Bundle options, nullboolean componentSpecified, trueActivityRecord[] outActivity, nullActivityContainer 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 sessionif (err == ActivityManager.START_SUCCESS && sourceRecord != null&& sourceRecord.task.voiceSession != null) {...}// 不走, voiceSession是nullif (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,所以不会进入此分支,参考:/QQxiaoqiang1573/article/details/77015379if (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, nullIVoiceInteractor voiceInteractor, nullint startFlags,0boolean doResume, trueBundle options, nullTaskRecord 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为falsefinal boolean launchTaskBehind = r.mLaunchTaskBehind&& !launchSingleTask && !launchSingleInstance&& (launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0; // 不走这里,因为没有设置 Intent.FLAG_ACTIVITY_NEW_TASKif (r.resultTo != null && (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {...}// 不走这个分支,因为没有设置 Intent.FLAG_ACTIVITY_NEW_DOCUMENTif ((launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0 && r.resultTo == null) {...}// 不走这里,因为没有设置 Intent.FLAG_ACTIVITY_NEW_TASKif ((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 是 0if ((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,设置给intentintent.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,不是当前的MainActivityif (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 这个 Flagif (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指向来源的ActivityStacktargetStack.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, falseboolean doResume, trueboolean keepCurTransition, falseBundle 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(); // 标记任务栈的顶层ActivityRecordr.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,patibilityInfoForPackageLocked(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 状态,则不允许启动 Activityif (!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,即 SecondActivityActivityRecord 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 就可以 resumeboolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0;// 暂停所有处于后台栈的 activityboolean 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 目前还是 nullif (mPausingActivity != null) {Slog.wtf(TAG, "Going to pause when pause is already pending for " + mPausingActivity);completePauseLocked(false);}// mResumedActivity 的值是 MainActivity 对应的 ActivityRecord 对象,不是 nullActivityRecord prev = mResumedActivity;if (prev == null) {// 不会进入此分支...}if (mActivityContainer.mParentActivity == null) {// Top level stack, not a child. Look for child stacks.// 暂停所有子栈的 activitymStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping, resuming, dontWait);}// 清空 mResumedActivity 的值mResumedActivity = null;// 把当前处于 resumed 状态的 MainActivity 对应的 ActivityRecord 赋值给 mPausingActivity 和 mLastPausedActivitymPausingActivity = 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 Binderimplements 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);}@Overridepublic 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_ACTIVITYfinished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,token, // obj 为 token(userLeaving ? 1 : 0) | (dontReport ? 2 : 0), // arg1 为 0configChanges); // 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 listenersArrayList<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,

@Overridepublic 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 为 nullif (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, trueboolean checkConfig,true

void startSpecificActivityLocked(ActivityRecord r,boolean andResume, boolean checkConfig) {// Is this activity's application already running?// 判断页面的应用是否已经在运行了,这里会返回 trueProcessRecord app = mService.getProcessRecordLocked(r.processName,r.info.applicationInfo.uid, true);r.task.stack.setLaunchTime(r);if (app != null && app.thread != null) {try {// 调用这里,真正启动ActivityrealStartActivityLocked(r, app, andResume, checkConfig); return;} catch (RemoteException e) {}}}

2.24 ActivityStatckSupervisor类的realStartActivityLocked()方法

ActivityRecord r,是在 ActivityStackSupervisor 的startActivityLocked() 方法中构造出的 ActivityRecord 对象,也就是 SecondActivity 对应的 ActivityRecord 对象ProcessRecord app, ProcessRecord 对象boolean andResume, trueboolean 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),pat, 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;patInfo = 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, patInfo);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, patInfo,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方法。

参考

Android 插件化原理解析——Hook机制之AMS&PMS

Android源码分析-Activity的启动过程

startActivity启动过程分析

Android四大组件之Activity–启动过程(上)

Android四大组件之Activity–启动过程(下)

ActivityRecord、TaskRecord、ActivityStack以及Activity启动模式详解

Activity启动流程详解(基于api28)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。