最近开始阅读 Android 源码,从 Activity 的启动过程开始入手。

打开 Activity 源码可以发现,startActivity(Intent intent) 方法实际上是调用 startActivityForResult(Intent intent, int requestCode):

1
2
3
4
@Override
public void startActivity(Intent intent) {
startActivityForResult(intent, -1);
}

继续跟进查看 startActivityForResult(Intent intent, int requestCode):
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
public void startActivityForResult(Intent intent, int requestCode) {
if (mParent == null) {
// 启动新的 Activity,核心功能在 ApplicationThread 类中完成
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(this,
mMainThread.getApplicationThread(),
mToken, this, intent, requestCode);
if (ar != null) {
// 发送结果
mMainThread.sendActivityResult(mToken, mEmbeddedID,
requestCode, ar.getResultCode(), ar.getResultData());
}
if (requestCode >= 0) {
// If this start is requesting a result, we can avoid making
// the activity visible until the result is received. Setting
// this code during onCreate(Bundle savedInstanceState)
// or onResume() will keep the
// activity hidden during this time, to avoid flickering.
// This can only be done when a result is requested because
// that guarantees we will get information back when the
// activity is finished, no matter what happens to it.
mStartedActivity = true;
}
} else {
mParent.startActivityFromChild(this, intent, requestCode);
}
}

打开 Instrumentation 类,查看 execStartActivity() 方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public ActivityResult execStartActivity(Context who, IBinder contextThread,
IBinder token, Activity target, Intent intent, int requestCode) {

IApplicationThread whoThread = (IApplicationThread) contextThread;
. . .
try {
intent.setAllowFds(false);
// 打开 Activity ,具体实现在 ApplicationThread 中
int result = ActivityManagerNative.getDefault().startActivity(
whoThread, intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
null, 0, token, target != null ? target.mEmbeddedID : null,
requestCode, false, false, null, null, false);
// 检查结果,如果 result < 0,则会抛出各种异常,如 ActivityNotFound 等
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
}
return null;
}

打开 ApplicationThread (在 ActivityThread 的中,为其内部类),会发现 schedule**Activity(..) 类似的方法,直接查看 scheduleLaunchActivity 方法:
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
public final void scheduleLaunchActivity(Intent intent, IBinder token,
int ident, ActivityInfo info, Configuration curConfig,
CompatibilityInfo compatInfo, Bundle state, List<ResultInfo> pendingResults,
List<Intent> pendingNewIntents, boolean notResumed, boolean isForward,
String profileName, ParcelFileDescriptor profileFd, boolean autoStopProfiler) {

ActivityClientRecord r = new ActivityClientRecord();

r.token = token;
r.ident = ident;
r.intent = intent;
r.activityInfo = info;
r.compatInfo = compatInfo;
r.state = state;

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

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

r.profileFile = profileName;
r.profileFd = profileFd;
r.autoStopProfiler = autoStopProfiler;

updatePendingConfiguration(curConfig);

queueOrSendMessage(H.LAUNCH_ACTIVITY, r);
}

构造一个 ActivityClientRecord 后,调用 queueOrSendMessage(..) 方法,交由一个继承 Handler 的 H 类处理。
查看 H 类的 handleMessage(Message msg),可以发现处理各种 Activity 的状态事件。
1
2
3
4
5
6
7
8
9
10
11
12
13
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + msg.what);
switch (msg.what) {
case LAUNCH_ACTIVITY: {
ActivityClientRecord r = (ActivityClientRecord)msg.obj;
r.packageInfo =
getPackageInfoNoCheck(r.activityInfo.applicationInfo, r.compatInfo);
// 真正启动 Activity 的地方
handleLaunchActivity(r, null);
} break;
. . .
}
}

在 handleLaunchActivity(ActivityClientRecord r, Intent customIntent) 中,会通过 performLaunchActivity(ActivityClientRecord r, Intent customIntent) 创建一个 Activity,查看方法实现:
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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);
}

// 从 Intent 中解析目标 Activity 的启动参数
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();
// 通过 ClassLoader 实例化 Activity 对象
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
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) {
ContextImpl appContext = new ContextImpl();
appContext.init(r.packageInfo, r.token, this);
appContext.setOuterContext(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);

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 方法,开始进入 Activity 启动的生命周期
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.state != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity,
r.state);
}
}
if (!r.activity.mFinished) {
activity.mCalled = false;
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;
}

至此,Activity 已经完成创建和启动,在 performLaunchActivity 执行完毕后,会继续执行 Activity 的 onResume 等方法。