我们从代码的角度来看一下 applicationContext 是什么。
Context.getApplicationContext()
是一个抽象的接口如下:
public abstract Context getApplicationContext();
文档中对 applicationContext
的说明如下:
Return the context of the single, global Application object of the
current process. This generally should only be used if you need a
Context whose lifecycle is separate from the current context, that is
tied to the lifetime of the process rather than the current component.
它在 ContextImpl
中的实现如下:
@Override
public Context getApplicationContext() {
return (mPackageInfo != null) ?
mPackageInfo.getApplication() : mMainThread.getApplication();
}
也就是我们常用到的 applicationContext
其实就是 Application
类的对象实例。
Application
是继承自 ContextWrapper
中的。
public class Application extends ContextWrapper implements ComponentCallbacks2 {
在 Android 开发中 Context 是一个非常重要的基础对象。 Activity 和 Application 继承自 ContextWrapper
是为了在 Activity
或者 Application
方便使用 Context
的接口。 这里使用了委托模式。其实 Context
接口的工作主要是由 ContextWrapper
的 baseContext
所实现。
public class ContextWrapper extends Context {
Context mBase;
protected void attachBaseContext(Context base) {
if (mBase != null) {
throw new IllegalStateException("Base context already set");
}
mBase = base;
}
对于 Application
来说,其 baseContext
是在实例化之后 attach
上去的。
// Instrumentation.java
static public Application newApplication(Class<?> clazz, Context context)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
Application app = (Application)clazz.newInstance();
app.attach(context);
return app;
}
// Application.java
/* package */ final void attach(Context context) {
attachBaseContext(context);
mLoadedApk = ContextImpl.getImpl(context).mPackageInfo;
}
baseContext
则是通过如下代码创建。
// ContextImpl.java
static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) {
if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
null);
context.setResources(packageInfo.getResources());
return context;
}
网友评论