【Android】关于上下文的种种传说

Context

  1. 中文直译为“上下文”
  2. SDK中对其说明如下

  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

看一段测试代码

    private Context mContext;
    public void method() { 
        mContext = this;
        mContext = MainActivity.this; 
        mContext = getApplicationContext(); 
        mContext = getBaseContext(); 
        Log.v("huangc","####  mContext="+ this );
        Log.v("huangc","####  MainActivity.this="+ MainActivity.this );
        Log.v("huangc","####  getApplicationContext()="+getApplicationContext() );
        Log.v("huangc","####  getBaseContext()="+ getBaseContext());
     } 

看日志输出

####  mContext=com.example.test4intent.MainActivity@302ffdcb
####  MainActivity.this=com.example.test4intent.MainActivity@302ffdcb
####  getApplicationContext()=android.app.Application@39c519a8
####  getBaseContext()=android.app.ContextImpl@26ad4cc1

可见大多数情况下

【1】 this == MainActivity.this

【2】this != getApplicationContext() != getBaseContext()

参考文档

http://blog.csdn.net/qinjuning/article/details/7310620

猜你喜欢

转载自my.oschina.net/u/2273965/blog/674765