本文转载 罗升阳的《Android应用程序窗口(Activity)的运行上下文环境(Context)的创建过程分析》。在他文章基础上,补充部分内容。知识版权归罗生阳所有。
本文,我们就从ActivityThread类的成员函数performLaunchActivity开始,分析一个Activity实例的创建过程,以便可以从中了解它的运行上下文(Context)环境的创建过程,如图1所示:
这个过程一共分为10个步骤,接下来我们就详细分析每一个步骤。
Step 1. ActivityThread.performLaunchActivity
public final class ActivityThread {
......
Instrumentation mInstrumentation;
......
private final Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
......
ComponentName component = r.intent.getComponent();
......
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent); // ----》Step 2. Instrumentation.newActivity
......
} catch (Exception e) {
......
}
try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
......
if (activity != null) {
ContextImpl appContext = new ContextImpl(); // ----》Step 4. new ContextImpl
......
appContext.setOuterContext(activity); // ----》Step 5. ContextImpl.setOuterContext
......
Configuration config = new Configuration(mConfiguration);
......
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r