Android应用Context详解及源码解析,安卓面试题及答案2020百度

本文详细探讨了Android中的Context,包括ContextWrapper和ContextThemeWrapper的源码解析,以及Activity、Service、Application中ContextImpl的实例化过程。通过源码分析,明确了每个组件的Context数量,并解释了如何通过Context访问资源。
摘要由CSDN通过智能技术生成

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在ActivityThread中实例化过程源码分析


在开始分析之前还是和《Android异步消息处理机制详解及源码分析》的3-1-2小节及《Android应用setContentView与LayoutInfl

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值