开会的时候,老大抛出的问题:this、Activity.this、getApplication之间的区别?Context到底指什么?
发现没几个人说得明白,自己也是对这些模模糊糊,于是就认真了解下。
1.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.
*/
public abstract class Context {
......
}
大致意思(参考CSDN大牛,自己表达不出这种意思):
1、它描述的是一个应用程序环境的信息,即上下文。
2、该类是一个抽象(abstract class)类,Android提供了该抽象类的具体实现类。
3、通过它我们可以获取应用程序的资源和类,也包括一些应用级别操作,例如:启动一个Activity,发送广播,接受Intent
信息 等。
Context就像是人的手,类或是方法就像是劳动工具,例如锄头等。要去劳动,就用手来操作劳动工具。
2.getApplication
是Activity和Service中的方法:
/** Return the application that owns this activity/service. */
public final Application getApplication() {
return mApplication;
}
private Application mApplication;
获得的是当前Activity&Service的应用程序Application对象。
3.getApplicationContext
Context中的抽象方法,在ContextImpl以及ContextWrapper中实现。
ContextImpl&
ContextWrapper均是
Context的子类。即在Application、Activity、Service中均可以使用。
/**
* Return the context of the single, global Application object of the
* current process. This generally should only be used if you need a
* Context whose lifecycle is separate from the current context, that is
* tied to the lifetime of the process rather than the current component.
*
*/
public abstract Context getApplicationContext();
返回一个Context对象,与
getApplication返回的对象没有太大的区别,但是在Application类中,没有定义getApplication方法。
4.
this
this关键字总是指向调用该方法的对象。
this可以代表任何对象,当this出现在某个方法体中的时候,它所代表的对象是不确定的,但它的类型是确定的,它所代表的对象只能是当前类,只有当这个方法被调用时,它所代表的对象才被确定下来:
谁在调用这个方法,this就代表谁。
在Activity中,则代表Activity的实例。
5.xxxActivity.this
具体到指xxxActivity的实例/对象。
如果在匿名内部类中使用this,则代表的是
匿名内部类的实例,此时如果需要的是Activity的实例,则需要传入
xxxActivity.this。
如果是在Activity中,则
this和
xxxActivity.this没有区别。
6.Context与Activity&Service&Application之间的继承关系
Context 是抽象类;
ContextImpl&
ContextWrapper均是
Context的子类
;
ContextWrapper中持有
ContextImpl的引用。
ContextThemeWrapper是
ContextWrapper的子类;
Service&Application是
ContextWrapper的子类;
Activity是
ContextThemeWrapper的子类;
参考文章:
http://blog.csdn.net/twlkyao/article/details/17635811
http://blog.csdn.net/iaiti/article/details/12871445
http://blog.csdn.net/qinjuning/article/details/7310620