源码分析:Activity的启动过程(2)

ActivityStackSupervisor#realStartActivityLocked(以下源码都是基于API25)

realStartActivityLocked方法中有一段非常重要的代码

1
2
3
4
5
6
7
8
9
10
11
12
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
//...

app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);

//...
}

  • 其中app是realStartActivityLocked方法传入的参数,其类型是ProcessRecord(包含当前正在运行的特定进程的完整信息)。app.thread的类型则是IApplicationThread。
  • IApplicationThread接口继承了IInterface接口,所以它是一个Binder类型的接口。该接口内部包含了大量启动、停止Activity的方法。该接口的最终实现者是ActivityThread的内部类ApplicationThread
    1
    2
    3
    public final class ActivityThread {
    private class ApplicationThread extends ApplicationThreadNative {...}
    }
1
2
public abstract class ApplicationThreadNative extends Binder
implements IApplicationThread {...}

ActivityThread.ApplicationThread#scheduleLaunchActivity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// we use token to identify this activity without having to send the
// activity itself back to the activity manager. (matters more with ipc)
@Override
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
int procState, Bundle state, PersistableBundle persistentState,
List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {

updateProcessState(procState, false);

ActivityClientRecord r = new ActivityClientRecord();

//一些r的配置

updatePendingConfiguration(curConfig);

sendMessage(H.LAUNCH_ACTIVITY, r); //H是ActivityThread的一个内部类,其继承自Handler
}

该方法的实现很简单,就是发送一个启动activity的消息交给H处理。

ActivityThread.H#handleMessage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private class H extends Handler {
//...

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

r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
handleLaunchActivity(r, null, "LAUNCH_ACTIVITY"); //继续调用
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;

//...
}
}

H对这条消息的处理是:调用ActivityThread的handleLaunchActivity方法启动activity

ActivityThread#handleLaunchActivity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
//...

Activity a = performLaunchActivity(r, customIntent);

if (a != null) {
//...

handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);

} else {
//...
}
}

其中,performLaunchActivity方法最终完成了activity对象的创建和启动,并且通过handleResumeActivity方法来调用该activity对象的onResume这一生命周期方法。

ActivityThread#performLaunchActivity

该方法主要完成了这几件事:

1. 从ActivityClientRecord中获取待启动的activity的组件信息

2. 通过Instrumentation的newActivity方法使用类加载器创建Activity对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent); //创建Activity对象并最终返回该对象
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
//...
}

3. 通过LoadedApk的makeApplication方法来尝试创建Application对象

1
2
3
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
//r是一个ActivityClientRecord(ActivityThread的静态内部类)对象
//r.packageInfo是一个LoadedApk对象

LoadedApk#makeApplication

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
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
if (mApplication != null) { //如果已经创建过Application,就直接返回该Application
return mApplication;
}

Application app = null;

try {
//...

app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
//与创建Activity对象类似,创建Application对象也是通过Instrumentation并使用类加载器完成的

} catch (Exception e) {
//...
}
mActivityThread.mAllApplications.add(app);
mApplication = app;

if (instrumentation != null) {
try {
instrumentation.callApplicationOnCreate(app); //调用Application的onCreate方法
} catch (Exception e) {
//...
}
}

return app;
}

可以看出,如果之前已经创建过Application对象,就直接返回该对象,这保证了一个应用只有一个Application对象。Application对象创建完毕后,会通过Instrumentation的callApplicationOnCreate方法来调用Application的onCreate方法

4. 创建ContextImpl对象并通过Activity的attach方法来完成一项重要数据的初始化

1
2
3
4
5
6
7
8
Context appContext = createBaseContextForActivity(r, activity);     //最终返回的是ContextImpl对象

//...

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);
  • ContextImpl是Context抽象类的具体实现,ContextImpl是通过Activity的attach方法来和Activity建立关联的。
  • attach方法除了关联ContextImpl和Activity,还会完成Window的创建并建立Activity和Windwo的关联,这样当Window接收到外部输入事件后就可以将事件传递给Activity。

5. 调用Activity的onCreate方法

1
2
3
4
5
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}

Activity的onCreate方法的调用,也意味着Activity已经完成了整个启动过程。

参考

  • 《Android开发艺术探索》
-------------    本文到此结束  感谢您的阅读    -------------
0%