You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1.9 KiB
1.9 KiB
谈谈你对 Context 的理解?
- 了解 Context 的作用
- 熟悉 Context 初始化流程
- 深入理解不同应用组件之间 Context 的区别
问题
- 应用里面有多少个 Context?不同的 Context 之间有什么区别?
- Activity 里的 this 和 getBaseContext 有什么区别?
- getApplication 和 getApplicationContext 有什么区别?
- 应用组件的构造,onCreate、attachBaseContext 调用顺序?
class ContextImpl extends Context {
final ActivityThread mMainThread;
final LoadedApk mPackageInfo;
private final ResourcesManager mResourcesManager;
private final Resource mResources;
private Resources.Theme mTheme = null;
private PackageManager mPackageManager;
final Object[] mServiceCache = SystemServiceRegistry.createServiceCache();
}
Context 是在哪创建的?
Application :
-
继承关系
Application <- ContextWrapper <- Context
-
调用顺序
<init> -> attachBaseContext -> onCreate
Activity:
private Activity performLaunchActivity() {
Activity activity = null;
activity = mInstrumentation.newActivity();
Application app = r.packageInfo.makeApplication();
Context appContext = createBaseContextForActivity(r, activity);
activity.attach(appContext, app, ...);
activity.onCreate();
return activity;
}
-
继承关系
Activity <- ContextThemeWrapper <- ContextWrapper
-
调用顺序
<init> -> attachBaseContext -> onCreate
Service:
private void handleCreateService(CreateServiceData data) {
Service service = null;
service = (Service) cl.loadClass(data.info.name).newInstance();
ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
context.setOuterContext(service);
Application app = packageInfo.makeApplication();
service.attach(context, app);
service.onCreate();
}