造成这种困惑的原因是有很多方法
access上下文,(表面上)没有明显的区别。
下面是四种最常见的方法
活动中的上下文。
getContext()
getBaseContext()
getApplicationContext()
getActionBar().getThemedContext() //new
什么是上下文?
我个人喜欢把上下文看作应用程序在任何给定时间的状态。应用程序上下文表示应用程序的全局或基本配置,活动或服务可以构建在它之上,并表示应用程序的配置实例或它的传递状态。
看看android。content的源代码。Context,你可以看到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.
What I take away from this is that Context provides a common implementation to access application level as well as system level resources. Application level resources may be accessing things like String resources [getResources()] or assets [getAssets()] and system-level resource is anything that you access with Context.getSystemService().
事实上,看看这些方法的评论,它们似乎强化了这个概念:
getSystemService(): Return the handle to a system-level service by name. The class of the returned object varies by the requested name.
getResources(): Return a Resources instance for your application’s package.
getAssets(): Return a Resources instance for your application’s package.
It may be worth pointing out that in the Context abstract class, all of the above methods are abstract! Only one instance of getSystemService(Class) has an implementation and that invokes an abstract method. This means, the implementation for these should be provided mostly by the implementing classes, which include:
ContextWrapper
Application
Activity
Service
IntentService
查看API文档,类的层次结构是这样的:
上下文
| - ContextWrapper
| - -应用
|— — 上下文主题包装器
| - - -活动
| - -服务
|— — 意图服务
Since we know that Context itself is not providing any insight, we move down the tree and take a look at the ContextWrapper and realize that there isn't much there either. Since Application extends ContextWrapper, there isn't much to look at over there either since it doesn't override the implementation provided by ContextWrapper. This means that the implementation for Context is provided by the OS and is hidden from the API. You can take a look at the concrete implementation for Context by looking at the source for the ContextImpl class.