Activity的启动流程

备注:Android 11源码

本文基于Android 11的源码分析,简要的跟踪以下Activity的启动流程,发现在一些细节已经发生变化,例如没有出现ActivityManagerService,而是出现了ActivityTaskManagerService

客户端的调用

当我们调用startActivity启动一个Actvity时,都会调用到startActivityForResult函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void startActivityForResult(
String who, Intent intent, int requestCode, @Nullable Bundle options) {
...
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, who,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, who, requestCode,
ar.getResultCode(), ar.getResultData());
}
cancelInputsAndStartExitTransition(options);
}

调用了Instrumentation对象的execStartActivity函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
...
try {
int result = ActivityTaskManager.getService().startActivity(whoThread,
who.getBasePackageName(), who.getAttributionTag(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()), token,
target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}

调用了ActivityTaskManager.getService().startActivity函数。

1
2
3
4
5
6
7
8
9
10
11
12
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}

private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
new Singleton<IActivityTaskManager>() {
@Override
protected IActivityTaskManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);//注释1
return IActivityTaskManager.Stub.asInterface(b);//注释2
}
};

通过getService函数实现,可见通过AIDL的形式调用了服务端的ActivityTaskManagerServicestartActivity函数。注释1得到名为activity_taskService引用,也就是IBinder类型的ATM引用。注释2将其转换成IActivityTaskManager类型对象,即服务端ATM在客户端的代表,客户端通过该代表与服务端交互。

服务端的处理

查看AIDL服务端ActivityTaskManagerServicestartActivity的调用。ActivityTaskManagerService是用来管理Activity和他们容器Stack的系统服务。

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

startActivity通过增加UserHandle.getCallingUserId()获取到用户ID。并调用了startActivityAsUser函数,主要进行一些权限检查,例如是否同个包名,是否在沙盒。

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
public int startActivityAsUser(IApplicationThread caller, String callingPackage,
String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
Bundle bOptions, int userId) {
...
return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
true /*validateIncomingUser*/);
}

private int startActivityAsUser(IApplicationThread caller, String callingPackage,
@Nullable String callingFeatureId, Intent intent, String resolvedType,
IBinder resultTo, String resultWho, int requestCode, int startFlags,
ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
//检测调用的包名是否与用户ID匹配
assertPackageMatchesCallingUid(callingPackage);
//判断调用者进程是否隔离
enforceNotIsolatedCaller("startActivityAsUser");

userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");

return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setCallingFeatureId(callingFeatureId)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setUserId(userId)
.execute();

}

getActivityStartController().obtainStarter函数返回了ActivityStarter对象,通过构造者模式设置相关属性之后,调用了excute函数。ActivityStarter主要根据intentflags负责如何启动Activity,以及设置和它相关联的栈。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int execute() {
try {
...
synchronized (mService.mGlobalLock) {
...
res = executeRequest(mRequest);
...
}
...
return getExternalResult(mRequest.waitResult == null ? res
: waitForResult(res, mLastStartActivityRecord));
}
} finally {
onExecutionComplete();
}
}

execute函数挺长的,主要根据之前的配置信息解析出必要的信息,例如从intent中解析出要启动Activity的相关信息activityInfo。其中调用executeRequest函数。该函数代码很长,主要进行几项检查,例如启动标志Flags和权限,以及解析相关信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private int executeRequest(Request request) {
final int launchFlags = intent.getFlags();
if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) {
...
final ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
callingPackage, callingFeatureId, intent, resolvedType, aInfo,
mService.getGlobalConfiguration(), resultRecord, resultWho, requestCode,
request.componentSpecified, voiceSession != null, mSupervisor, checkedOptions,
sourceRecord);
mLastStartActivityRecord = r;

mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
restrictedBgActivity, intentGrants);

if (request.outActivity != null) {
request.outActivity[0] = mLastStartActivityRecord;
}

return mLastStartActivityResult;
}

executeRequest函数最终将Activity相关信息封装到ActivityRecord对象中,然后调用startActivityUnchecked函数。

1
2
3
4
5
6
7
8
9
10
11
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {

...
result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask,restrictedBgActivity,intentGrants);
...
return result;
}

调用了startActivityInner函数。这里就是判断Activity的启动模式,是添加到已有栈顶或者传递新的intent给已启动的Activity

1
2
3
4
5
6
7
8
9
10
int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
...
mRootWindowContainer.resumeFocusedStacksTopActivities(
mTargetStack, mStartActivity, mOptions);
...
return START_SUCCESS;
}

调用了RootWindowContainer对象的resumeFocusedStacksTopActivities函数

1
2
3
4
5
6
7
boolean resumeFocusedStacksTopActivities(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
...
result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
...
return result;
}

调用了ActivityStackresumeTopActivityUncheckedLocked函数。此时就是将Activity栈顶的Activity进行resume

1
2
3
4
5
6
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
...
result = resumeTopActivityInnerLocked(prev, options);
...
return result;
}

调用了resumeTopActivityInnerLocked函数,主要住一些ActivityRecord类状态的判断和更新。

1
2
3
4
5
6
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
...
mStackSupervisor.startSpecificActivity(next, true, true);
...
return true;
}

然后调用了ActivityStatckSupervisorstartSpecificActivity函数。

1
2
3
4
5
void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
...
realStartActivityLocked(r, wpc, andResume, checkConfig);
...
}

调用realStartActivityLocked函数。

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
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
...
//1
final ClientTransaction clientTransaction = ClientTransaction.obtain(
proc.getThread(), r.appToken);

//2
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
r.getSavedState(), r.getPersistentSavedState(), results, newIntents,
dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));

// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);

//注释3
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
...
return true;
}

注释1创建了ClientTransaction对象,主要保存一些发送给客户端的信息和回调。例如注释2添加了LaunchActivityItem对象回调,该回调主要用来启动Activity,也是我们关心的地方。然后注释3执行ClientTransaction对象。mService.getLifecycleManager()返回的是一个ClientLifecycleManager对象。

1
2
3
4
5
6
7
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule();
if (!(client instanceof Binder)) {
transaction.recycle();
}
}

调用了ClientTransactionschedule函数。

1
2
3
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}

这里的mClientIApplicationThread,也就是以AIDL跨进程通信。具体的实现类其实是ActivityThread的内部类ApplicationThread

客户端的处理

1
2
3
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}

调用了ActivityThreadscheduleTransaction函数,但ActivityThread没有该方法,在其父类ClientTransactionHandler找到。

1
2
3
4
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}

调用了抽象方法sendMessage发送了参数为ActivityThread.H.EXECUTE_TRANSACTION的消息。回到ActivityThreadsendMessage有很多重载函数。最终还是调用了mHsendMessage函数。mH是H类实例,是Handler的子类。

1
2
3
4
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
...
mH.sendMessage(msg);
}

定位到H的handleMessage函数的EXECUTE_TRANSACTION分支。

1
2
3
4
5
6
7
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
if (isSystem()) {
transaction.recycle();
}
break;

调用execute函数。

1
2
3
4
5
6
public void execute(ClientTransaction transaction) {
...
executeCallbacks(transaction);
executeLifecycleState(transaction);
...
}

查看executeCallbacks函数。

1
2
3
4
5
6
7
8
9
10
11
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
...
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
...
item.execute(mTransactionHandler, token, mPendingActions);
...
}
}
}

executeCallbacks函数主要循环执行ClientTransitions对象的所有的回调,而我们在前面看到设置了LaunchActivityItem回调。

1
2
3
4
5
6
7
8
9
10
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}

调用了ClientTransactionHandlerhandleLaunchActivity函数,是一个抽象方法,定位到ActivityThread

1
2
3
4
5
6
7
8
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
...
final Activity a = performLaunchActivity(r, customIntent);
...

return a;
}

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
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 Context上下文
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
//创建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);
}
}

//创建Applicaton 对象
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
...
appContext.getResources().addLoaders(
app.getResources().getLoaders().toArray(new ResourcesLoader[0]));

appContext.setOuterContext(activity);
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, window, r.configCallback,
r.assistToken);
...
//调用onCreate函数
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
...
return activity;
}

可以看到performLaunchActivity创建了Activity实例,调用了callActivityOnCreate函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void callActivityOnCreate(Activity activity, Bundle icicle,
PersistableBundle persistentState) {
prePerformCreate(activity);
activity.performCreate(icicle, persistentState);
postPerformCreate(activity);
}

final void performCreate(Bundle icicle, PersistableBundle persistentState) {
...
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
...
}

可见,最后调用了ActivityonCreate函数。

总结

其实本文只是跟一下Activity的启动流程,其中涉及到了很多细节都忽略了,例如最后Context上下文的创建,这个留到其他文章具体点的分析。也就是从整体思路了解Activity的启动流程。