不知不觉,Android学习笔记已经写到了第7篇,这篇主要是介绍Context,上下文,因为之前经常会碰到它,但是对它并不是十分了解,所以最近参考了一些网上的资料,加上自己的一些整理,简单地对它进行了一点学习总结。
一、Context概述
二、Context初探
三、Context深入
四、Context总结
记得之前做过一个简单的Demo,我把几个用到的资源文件放在assets目录下,之后我准备写个util工具类专门负责读取这些文件,然后想在其中通过getAssets获取Assets资源管理器,但是始终有问题,后来百度的时候找到答案,在util工具类要有个Context实例,必须通过它来获取AssetManager。
一、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,上下文,用户与操作系统操作的一个过程,这个对象描述的是一个应用程序环境的全局信息。它是一个Android系统提供具体实现的抽象类,可以让我们访问应用具体的资源和类文件,包括一些应用级别的操作,例如启动Activity,广播,以及接收意图等等。
二、Context初探
我们可以先大致看下Context类里面的结构。
可以看到Context类里有很多抽象方法都是我们比较熟悉的,比如获取资源管理器,获取内容解析器,activity、broadcast、service等组件的常用操作,都可以找到。这时,我们再看下Activity类继承关系。
还有Service类继承关系
这下,我们应该清楚了,Service和Activity类以及Application类都是Context类的子类,下面这张图很直观。
三、Context深入
与Context有关的几个类主要如下。
- ContextWrapper
Context的直接子类,wrapper意为包装,这个类主要是代理实现Context类里的所有操作,可以看到其内部有个Context实例mBase。
public class ContextWrapper extends Context {
Context mBase;
public ContextWrapper(Context base) {
mBase = base;
}
/**
* 创建Application、Service、Activity,会调用该方法给mBase属性赋值
* @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;
}
...
}
2.ContextThemeWrapper
继承了ContextWrapper的子类,可以允许我们修改包装的context里的主题。我们可以看到Activity是继承这个类的,而Service没有继承这个类,因为Service不需要主题。
public class ContextThemeWrapper extends ContextWrapper {
private int mThemeResource;
private Resources.Theme mTheme;
private LayoutInflater mInflater;
private Configuration mOverrideConfiguration;
private Resources mResources;
public ContextThemeWrapper() {
super(null);
}
public ContextThemeWrapper(Context base, @StyleRes int themeResId) {
super(base);
mThemeResource = themeResId;
}
public ContextThemeWrapper(Context base, Resources.Theme theme) {
super(base);
mTheme = theme;
}
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
}
...
}
四、Context总结
在平常的开发中,我们使用Context的地方还是比较多的,下面是些主要的场景。
- ContentProvider、BroadcastReceiver之所以在上述表格中,是因为在其内部方法中都有一个context用于使用。
- 可以看到有一些NO上添加了一些数字,其实这些从能力上来说是YES,但是为什么说是NO呢?解释如下。
- 数字1:启动Activity在这些类中是可以的,但是需要创建一个新的task。一般情况不推荐。
- 数字2:在这些类中去layout inflate是合法的,但是会使用系统默认的主题样式,如果你自定义了某些样式可能不会被使用。
- 数字3:在receiver为null时允许,在4.2或以上的版本中,用于获取黏性广播的当前值。(可以无视)
最后,关于Context的使用有一个注意的地方就是,和UI相关的方法基本都不建议或者不可使用Application,应该使用Activity作为Context来处理;其他的一些操作,Service,Activity,Application等实例都可以,同时,使用中一定要注意Context引用的持有,防止内存泄漏。