*/
public abstract class Context {
…
}
看见没有,抽象类Context ,提供了一组通用的API。
再来看看Context的实现类ContextImpl源码注释:
/**
-
Common implementation of Context API, which provides the base
-
context object for Activity and other application components.
*/
class ContextImpl extends Context {
private Context mOuterContext;
…
}
该类实现了Context类的所有功能。
再来看看Context的包装类ContextWrapper源码注释:
/**
-
Proxying implementation of Context that simply delegates all of its calls to
-
another Context. Can be subclassed to modify behavior without changing
-
the original Context.
*/
public class ContextWrapper extends Context {
Context mBase;
public ContextWrapper(Context base) {
mBase = base;
}
/**
-
Set the base context for this ContextWrapper. All calls will then be
-
delegated to the base context. Throws
-
IllegalStateException if a base context has already been set.
-
@param base The new base context for this wrapper.
*/
protected void attachBaseContext(Context base) {
if (mBase != null) {
throw new IllegalStateException(“Base context already set”);
}
mBase = base;
}
…
}
该类的构造函数包含了一个真正的Context引用(ContextImpl对象),然后就变成了ContextImpl的装饰着模式。
再来看看ContextWrapper的子类ContextThemeWrapper源码注释:
/**
-
A ContextWrapper that allows you to modify the theme from what is in the
-
wrapped context.
*/
public class ContextThemeWrapper extends ContextWrapper {
…
}
该类内部包含了主题Theme相关的接口,即android:theme属性指定的。
再来看看Activity、Service、Application类的继承关系源码:
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory2,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks2,
Window.OnWindowDismissedCallback {
…
}
public abstract class Service extends ContextWrapper implements ComponentCallbacks2 {
…
}
public class Application extends ContextWrapper implements ComponentCallbacks2 {
…
}
看见没有?他们完全符合上面我们绘制的结构图与概述。
2-3 解决应用Context个数疑惑
有了上面的Context继承关系验证与分析之后我们来看下一个应用程序到底有多个Context?
Android应用程序只有四大组件,而其中两大组件都继承自Context,另外每个应用程序还有一个全局的Application对象。所以在我们了解了上面继承关系之后我们就可以计算出来Context总数,如下:
APP Context总数 = Application数(1) + Activity数(Customer) + Service数(Customer);
到此,我们也明确了Context是啥,继承关系是啥样,应用中Context个数是多少的问题。接下来就有必要继续深入分析这些Context都是怎么来的。
【工匠若水 http://blog.csdn.net/yanbober 转载烦请注明出处,尊重分享成果】
3 各种Context在ActivityThr