Launcher启动流程-AMS部分

AMS逻辑执行

调用者权限验证 AMS.startActivityAsUser

主要是AMS的startActivityAsUser中的逻辑

在AMS的startActivity中

1
2
3
4
5
6
7
8
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}

UserHandle.getCallingUserId() 会获得调用者的UserId,AMS会根据这个UserId来确定调用者的权限

获取启动组件信息 startActivityMyWait

主要是 startActivityMyWait中的逻辑

在步骤 startActivityMyWait 的源码中通过 resolveIntent 函数使用PMS去解析参数intent中的内容,来获得更多的Activity的启动信息.

对应代码

1
ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId);

之后保存在 ActivityInfo 中

1
ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);

PMS在安装一个应用程序的过程中,会对他的配置文件(AndroidManifest.xml)进行解析,从而得到他的组件信息

运行环境检查 ActivityStarter.startActivity

在ActivityStarter的 startActivity 中

分为以下几个步骤

  1. 处理 FLAG_ACTIVITY_FORWARD_RESULT 标志

比如三个Activity,A –> B –> C,如果A想要会的C的setResult,就要带上这个 flag

对应代码

1
if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) {}
  1. 检查caller的app是否存在,如果不存在 返回 error 为err = ActivityManager.START_PERMISSION_DENIED,直接终止AMS的运行,如果存在,通过AMS中的 ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>()来获取caller所在的进程信息 ProcessRecord

caller 指向的是应用程序进程的ApplicationThread对象

对应代码为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
ProcessRecord callerApp = null;
if (caller != null) {
callerApp = mService.getRecordForAppLocked(caller);
if (callerApp != null) {
callingPid = callerApp.pid;
callingUid = callerApp.info.uid;
} else {
err = ActivityManager.START_PERMISSION_DENIED;
}
}


//循环获取到进程信息
final ArrayMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
for (int i = pmap.size()-1; i >= 0; i--) {
final SparseArray<ProcessRecord> procs = pmap.valueAt(i);
for (int j = procs.size()-1; j >= 0; j--) {
final ProcessRecord proc = procs.valueAt(j);
if (proc.thread != null && proc.thread.asBinder() == threadBinder) {
return proc;
}
}
}

//err 错误码
if (err != START_SUCCESS) {
if (resultRecord != null) {
resultStack.sendActivityResultLocked(
-1, resultRecord, resultWho, requestCode, RESULT_CANCELED, null);
}
ActivityOptions.abort(options);
return err;
}
  1. 创建临时的 ActivityRecord,只为了后面的调用过程做对比,不一定会被添加到AMS里的

对应代码

1
2
3
4
ActivityRecord r = new ActivityRecord(...)
if (outActivity != null) {
outActivity[0] = r;
}
  1. 检查当前是否允许切换Activity,不允许的情况一般发生在当前已经暂停的正在执行的Activity,正在等待下一个Activity启动时,不能够进行切换,如果是这样,就添加到 mPendingActivityLaunches 列表中,等系统恢复后再继续执行

对应代码

1
2
3
4
5
6
7
8
9
10
11
if (voiceSession == null && (stack.mResumedActivity == null
|| stack.mResumedActivity.info.applicationInfo.uid != callingUid)) {
if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid,
realCallingPid, realCallingUid, "Activity start")) {
PendingActivityLaunch pal = new PendingActivityLaunch(r,
sourceRecord, startFlags, stack, callerApp);
mPendingActivityLaunches.add(pal);
ActivityOptions.abort(options);
return ActivityManager.START_SWITCHES_CANCELED;
}
}
  1. 判断 mPendingActivityLaunches列表中是否有等待的Activity需要启动,如果有,优先启动

对应代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
doPendingActivityLaunchesLocked(false);

final void doPendingActivityLaunchesLocked(boolean doResume) {
while (!mPendingActivityLaunches.isEmpty()) {
final PendingActivityLaunch pal = mPendingActivityLaunches.remove(0);
final boolean resume = doResume && mPendingActivityLaunches.isEmpty();
try {
startActivity(pal.r, pal.sourceRecord, null, null, pal.startFlags, resume, null,
null, null /*outRecords*/);
} catch (Exception e) {
pal.sendErrorResult(e.getMessage());
}
}
}

这个函数里的 startActivity 会去调用 ActivityStarter的 startActivityUnchecked,如果没有要处理的,就执行后续的startActivity,它同样也会调用 startActivityUnchecked

处理栈管理 startActivityUnchecked

作用
判断以何种方式来启动指定的Activity,找到或者创建合适的Task

主要是 startActivityUnchecked 中的逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
  private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
//初始化启动Activity的各种配置,在初始化前会重置各种配置再进行配置,这些配置包括:ActivityRecord、Intent、TaskRecord和LaunchFlags(启动的FLAG)等等
setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
voiceInteractor);
//计算出启动的FLAG,并将计算的值赋值给mLaunchFlags
computeLaunchingTaskFlags();
computeSourceStack();
//将mLaunchFlags设置给Intent,达到设定Activity的启动方式的目的
mIntent.setFlags(mLaunchFlags);
...
//启动根Activity时会将Intent的Flag设置为FLAG_ACTIVITY_NEW_TASK
if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
&& (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
newTask = true;
//创建新的TaskRecord,TaskRecord用来描述一个Activity任务栈
result = setTaskFromReuseOrCreateNewTask(
taskToAffiliate, preferredLaunchStackId, topStack);
} else if (mSourceRecord != null) {
result = setTaskFromSourceRecord();
} else if (mInTask != null) {
result = setTaskFromInTask();
} else {
setTaskToCurrentTopOrCreateNewTask();
}
...
if (mDoResume) {
final ActivityRecord topTaskActivity =
mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetStack.isFocusable()
|| (topTaskActivity != null && topTaskActivity.mTaskOverlay
&& mStartActivity != topTaskActivity)) {
...
} else {
if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
mTargetStack.moveToFront("startActivityUnchecked");
}
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
mOptions);
}
} else {
mTargetStack.addRecentActivityLocked(mStartActivity);
}
...

}

mDoResume 的值是由ActivityStarted的startActivity传递而来,为true

computeLaunchingTaskFlags

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
private void computeLaunchingTaskFlags() {
//TaskRecord类型的mInTask为null时,说明Activity要加入的栈不存在
if (mSourceRecord == null && mInTask != null && mInTask.getStack() != null) {
//解决的问题就是Activity要加入的栈不存在时如何计算出启动的FLAG
final Intent baseIntent = mInTask.getBaseIntent();
final ActivityRecord root = mInTask.getRootActivity();
...
if (root == null) {
final int flagsOfInterest = FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK
| FLAG_ACTIVITY_NEW_DOCUMENT | FLAG_ACTIVITY_RETAIN_IN_RECENTS;
mLaunchFlags = (mLaunchFlags & ~flagsOfInterest)
| (baseIntent.getFlags() & flagsOfInterest);
mIntent.setFlags(mLaunchFlags);
mInTask.setIntent(mStartActivity);
mAddingToTask = true;
} else if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
mAddingToTask = false;

} else {
mAddingToTask = true;
}

mReuseTask = mInTask;
} else {
mInTask = null;
if ((mStartActivity.isResolverActivity() || mStartActivity.noDisplay) && mSourceRecord != null
&& mSourceRecord.isFreeform()) {
mAddingToTask = true;
}
}

if (mInTask == null) {
//mSourceRecord 用于描述“初始Activity” 就是栈中的第一个Activity
if (mSourceRecord == null) {
if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) == 0 && mInTask == null) {
//设置位 操作 ,设置 flag,表示创建一个新栈
mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
}
} else if (mSourceRecord.launchMode == LAUNCH_SINGLE_INSTANCE) {
//如果“初始Activity”所在的栈只允许有一个Activity实例,则也需要创建一个新栈
mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
} else if (mLaunchSingleInstance || mLaunchSingleTask) {
//如果Launch Mode设置了singleTask或singleInstance,则也要创建一个新栈
mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
}
}
}

开始真正启动

resumeFocusedStackTopActivityLocked 的调用链中会调用到 resumeTopActivityInnerLocked,该函数的作用是暂停Activity等操作,会在 pause-Activity部分讲解

resumeFocusedStackTopActivityLocked 最终调用 startSpecificActivityLocked,该函数有两个重要方法

realStartActivityLockedstartProcessLocked

startProcessLocked 的作用在应用进程部分分析过,他的作用是开启新的进程

realStartActivityLocked 看名字就应该知道,就是真正启动Activity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
//获取即将要启动的Activity的所在的应用程序进程
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);
r.getStack().setLaunchTime(r);

if (app != null && app.thread != null) {
try {
if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
|| !"android".equals(r.info.packageName)) {
app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode,
mService.mProcessStats);
}
realStartActivityLocked(r, app, andResume, checkConfig);
return;
} catch (RemoteException e) {
}
}
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}

注意这个 startProcessLocked,如果进程没启动的时候就会启动进程,startProcessLocked流程做过分析,最终他会调用ActivityThread的main函数,在ActivityThread的main函数中,通过Binder的方式告知AMS,我的新进程已经启动完毕了,AMS收到后,调用 attachApplication ,attachApplication 中调用 bindApplication, 并且还会在 bindApplication 结束后,调用下面的代码

1
2
3
4
5
6
7
8
9
if (normalMode) {
try {
if (mStackSupervisor.attachApplicationLocked(app)) {
didSomething = true;
}
} catch (Exception e) {
badApp = true;
}
}

该函数会去查看在该进程中是否有等待的Activity需要去处理

并且调用 attachApplicationLocked,注意这个函数有不同的重载方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
final String processName = app.processName;
boolean didSomething = false;
for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
final ActivityStack stack = stacks.get(stackNdx);
if (!isFrontStack(stack)) {
continue;
}
//获取前台stack中栈顶第一个非finishing的Activity
ActivityRecord hr = stack.topRunningActivityLocked(null);
if (hr != null) {
if (hr.app == null && app.uid == hr.info.applicationInfo.uid
&& processName.equals(hr.processName)) {
try {
//真正的启动Activity
if (realStartActivityLocked(hr, app, true, true)) {
didSomething = true;
}
} catch (RemoteException e) {
throw e;
}
}
}
}
}
if (!didSomething) {
//启动Activity不成功,则确保有可见的Activity
ensureActivitiesVisibleLocked(null, 0);
}
return didSomething;
}

可以看到 ,它调用的也是 realStartActivityLocked

如果要启动的Activity所在的进程存在,则调用 realStartActivityLocked

在realStartActivityLocked 中,先调用 app.thread.scheduleLaunchActivity. 这里的app.thread类型为IApplicationThread,是个Binder接口,他的服务端实现是ActivityThread的 ApplicationThread

首先,Binder的客户端是通过AIDL生成的,因此 app.thread.scheduleLaunchActivity 一定是通过Binder驱动发送数据给服务端,也就是ApplicationThread

到此为止,AMS的工作已经处理结束,后面就是处理新进程,也就是回到我们启动Activity的进程

Activity 创建

在 ApplicationThread 中的scheduleLaunchActivity函数处理也很简单

1
2
3
4
5
6
7
8
ActivityClientRecord r = new ActivityClientRecord();

r.token = token;
......

updatePendingConfiguration(curConfig);

sendMessage(H.LAUNCH_ACTIVITY, r);

使用Handler发送消息,之后调用 handleLaunchActivity

handleLaunchActivity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
unscheduleGcIdler();
mSomeActivitiesChanged = true;

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

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

performLaunchActivity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

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

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

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

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

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

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

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

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

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

mActivities.put(r.token, r);

} catch (Exception e) {
...
}

return activity;
}

到此,正式进入了Activity的onCreate, onStart, onResume这些生命周期的过程

总结

Launcher 启动流程

  1. 点击桌面App图标,Launcher进程采用Binder向 AMS 发起startActivity请求
  2. AMS 接收到请求后,向zygote进程发送创建进程的请求
  3. Zygote进程fork出新的子进程,即App进程
  4. App进程启动完成后(ActivityThread.main中的操作过程),通过Binder向 AMS 进程发起 attachApplication 请求
  5. AMS 在收到请求后,进行一系列准备工作后,再通过binder向App进程发送scheduleLaunchActivity请求
  6. App进程的binder线程(ApplicationThread)在收到请求后,通过handler向主线程发送LAUNCH_ACTIVITY消息
  7. 主线程在收到Message后,创建目标Activity,并回调Activity.onCreate()等方法

Binder相关

  1. 应用程序通过 IActivityManager 这个Binder模块的接口来通信,通过 ActivityManagerProxy发送给AMS
  2. IActivityManager 的服务端 AMS 接收到消息后进行处理
  3. AMS 处理结束后,通过 IApplicationThread 这个Binder模块的接口来通信,通过 ApplicationThreadProxy进行发送给应用程序
  4. IApplicationThread 的服务端为应用程序中的 ApplicationThread
  5. 应用程序接收到消息后进行处理