Android Context们之间的关系
此文章内容参考自刘望舒此文章 Android深入理解Context
Context的继承关系
ApplicationContext
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
if (mApplication != null) {//1
return mApplication;
}
...
try {
...
java.lang.ClassLoader cl = getClassLoader();
...
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);//2
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);//3
appContext.setOuterContext(app);//4
} catch (Exception e) {
...
}
mActivityThread.mAllApplications.add(app);
mApplication = app;//5
...
return app;
}
- Application 继承自Context,通过attach方法持有ContextImpl
- ContextImpl通过setOuterContext 持有 Application
Activity Context
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);//1
...
}
} catch (Exception e) {
...
}
try {
...
if (activity != null) {
Context appContext = createBaseContextForActivity(r, activity);//2
...
/**
*3
*/
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);
...
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);//4
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
...
}
return activity;
}
private Context createBaseContextForActivity(ActivityClientRecord r, final Activity activity) {
...
ContextImpl appContext = ContextImpl.createActivityContext(
this, r.packageInfo, r.token, displayId, r.overrideConfig);//1
appContext.setOuterContext(activity);//2
Context baseContext = appContext;
...
return baseContext;
}
- ContextImpl 通过setOuterContext 方法持有activity
- activity通过attach 方法持有 ContextImpl
- activity attach方法的时候,会同时创建PhoneWindow,并绑定到
Service Context
private void handleCreateService(CreateServiceData data) {
...
try {
if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
ContextImpl context = ContextImpl.createAppContext(this, packageInfo);//1
context.setOuterContext(service);
Application app = packageInfo.makeApplication(false, mInstrumentation);
service.attach(context, this, data.info.name, data.token, app,
ActivityManagerNative.getDefault());//2
service.onCreate();
...
} catch (Exception e) {
...
}
}
- ContextImpl 通过setOuterContext 方法持有Service
- Service 通过attach 方法持有ContextImpl
- Service 同时通过attach 持有application