Android Context

本文详细介绍了Android中Context的作用及其实现原理。Context作为抽象类提供了应用程序环境的全局信息,包括访问资源、启动Activity及广播Intent等功能。文章进一步解析了Context的继承体系及其在Activity中的绑定过程。

Context简介

/**
 * Interface to global information about an application environment.  This is
 * an abstract class whose implementation is provided by
 * the Android system.  It
 * allows access to application-specific resources and classes, as well as
 * up-calls for application-level operations such as launching activities,
 * broadcasting and receiving intents, etc.
 *
 * Context描述了一个应用程序环境的全局信息。
 * 它是一个抽象类,由系统提供它的实现方法。
 * 通过它可以访问application中的资源和类,进行一些应用级别的操作,比如启动activity、broadcasting、
 * 接受intent等。
 */

Context相关类的继承方式

1、Context是一个抽象类,ContextImpl是其实现。所有有关Context的调用实际上都是ContextImpl实现的。

2、Context有一个子类是ContextWrapper,ContextWrapper中持有一个ContextImpl的实例。对ContextWrapper有关Context的接口调用ContextWrapper都会通过ContextImpl来实现。这里使用到了装饰者模式。有关装饰者模式,具体可以参考https://my.oschina.net/u/3026396/blog/784237

3、ContextWrapper有一个子类是ContextThemeWrapper,顾名思义它是跟界面相关的ContextWrapper。

4、Application、Service继承于ContextWrapper。Activity继承于ContextThemeWrapper。

Context和Activity的绑定过程

ActivityManagerService -> ActivityThread的main()程序主入口 -> 创建Handler -> 接受事件(比如LAUNCH_ACTIVITY、BIND_APPLICATION等) -> LaunchAtivity为例,handleLaunchActivity() -> performLaunchActivity()中

1.通过Instrumentation构造一个Activity对象

2.通过Instrumentation构造一个Application对象

3.通过createBaseContextForActivity()创建ContextImpl实例,通过setOuterContext和Activity对象绑定

4.获取Configuration对象

5.通过attach将context保存到Activity中

 

PS:ActivityManagerService借助ActivityStack是来把所有的Activity按照后进先出的顺序放在一个堆栈中;对于每一个应用程序来说,都有一个ActivityThread来表示应用程序的主进程,而每一个ActivityThread都包含有一个ApplicationThread实例,它是一个Binder对象,负责和其它进程进行通信。

 

 

转载于:https://my.oschina.net/u/3026396/blog/791855

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值