Context
1.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.
*/
以上是api-28中google官方对context的注释,大概翻译如下:
1.是对应用上下文的描述;
2.是抽象类;
3、通过它我们可以获取应用程序的资源和类,也包括一些应用级别操作。
Context类它有两个具体的实现子类:ContextImpl和ContextWrapper。其中ContextWrapper类,如其名所言,这只是一个包装而已,ContextWrapper构造函数中必须包含一个真正的Context引用,同时ContextWrapper中提供了attachBaseContext()用于给ContextWrapper对象中指定真正的Context对象,调用ContextWrapper的方法都会被转向其所包含的真正的Context对象。ContextThemeWrapper类,其内部包含了与主题(Theme)相关的接口,只有Activity才需要主题,Service是不需要主题的,因为Service是没有界面的后台场景,所以Service直接继承于ContextWrapper,Application同理。而ContextImpl类则真正实现了Context中的所有函数,应用程序中所调用的各种Context类的方法,其实现均来自于该类。
一、Context相关类的继承关系
源代码(部分)如下:
public abstract class Context {
...
//获得系统级服务
public abstract Object getSystemService(String name);
//通过一个Intent启动Activity
public abstract void startActivity(Intent intent);
//启动Service
public abstract ComponentName startService(Intent service);
//根据文件名得到SharedPreferences对象
public abstract SharedPreferences getSharedPreferences(String name,int mode); //Activity token 弹框中有用到
public IBinder getActivityToken();
//
public ApplicationInfo getApplicationIn