Context类浅析

Context类浅析


Context

Context
n. 语境; 上下文; 背景; 环境;

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.

在android编程中,我们经常与Context类打交道,Context被翻译为上下文,代表了一个andorid应用程序的完整的工作环境,通过它,我们可以访问应用程序的资源和类,并且执行一些application-level 的操作。
平常编程中接触频繁的activity,service,application都与Context联系紧密,都与Context有继承关系。
这里写图片描述


ContextWrapper

Contextlml类是Context的具体实现类。
目前我对ContextIml的了解还有待进一步总结,讨论一下ContextWrapper类。
正如名称一样,ContextWrapper提供了对Context类的一种包装。

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.

这里写图片描述

在ContextWrapper类构造方法中
这里写图片描述

定义了一个Context引用mBase,并在Context类中使用操作。
这里写图片描述
由此可以得出,activity,service,application中所有与“上下文”的操作均由mBase操作。


Activitycontext与Applicationcontect

这是两种最常见,最经常使用的Context。
Activity_context跟Activity的生命周期有关,当与其有联系的Activity销毁时,该context即销毁,对于同一个Application,可能有多个Activity销毁,即对应该Context销毁。
Application_context与一个Application有关,伴随着Application的一生,随着Application的销毁而销毁。
怎样获取Applicationcontect呢?通常通过Context.getApplicationContext或者Activity.getApplication方法获取



因为Context的性质,我们使用Context时必须注意不要造成内存泄漏。一般引用时需要注意以下几个问题:

  1. 保证activity_context对象与对应的activity的本身的生命周期一致,尽量不要定义为static类型。
  2. 生命周期长的对象,可以使用application context。
  3. 避免非静态的内部类,尽量使用静态类,避免生命周期问题,注意内部类对外部对象引用导致的生命周期变化




安卓新手进阶中…….
It is not what you do in a while that shaps your future but what you do frequently.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值