关于Context的理解

Context

翻译成中文大概是:“上下文,背景”的意思。

这是一个抽象类,这个类的具体左右是什么呢?

Api文档是这样描述的:

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.

下面摘自http://stackoverflow.com/questions/3572463/what-is-context-in-android的描述

As the name suggests, its the context of current state of the application/object. It lets newly created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity, package/application)

You can get the context by invoking getApplicationContext()getContext(),getBaseContext() or this (when in the activity class).

Typical uses of context:

  • Creating New objects: Creating new views, adapters, listeners:

    TextView tv = new TextView(getContext());
    ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);
    
  • Accessing Standard Common Resources: Services like LAYOUT_INFLATER_SERVICE, SharedPreferences:

    context.getSystemService(LAYOUT_INFLATER_SERVICE);
    this.getResources().get***
     getApplicationContext().getSharedPreferences(*name*, *mode*);
    (AlarmManager)getSystemService(Context.ALARM_SERVICE);//闹钟相关
    Context.getSystemService(Context.CONNECTIVITY_SERVICE);//网络服务相关
  • Accessing Components Implicitly: Regarding content providers, broadcasts, intent

    getApplicationContext().getContentResolver().query(uri, ...);

 

主要的作用有3个:

1.创建对象

2.获取公共资源文件,获取系统的某些管理器,比如控制电源,网络,等等

3.调用系统组件

Context是一个抽象类,我们先看下他的继承方式:

 

java.lang.Object
   ↳ android.content.Context
Known Direct Subclasses
Known Indirect Subclasses

可以看出,常见的Activity,Application等都是继承自Context的子类ContextWrapper。

这里不得不提下:由于Context是抽象类,没有具体的实现,他有两个实现类,其中一个就是ContextWrapper,一个包装类。这个包装类就替Context实现具体的操作,比如获取公共的资源

 

public class ContextWrapper{
    Context mContext

    public ContextWrapper(Context ctx){
        mContext = ctx
    }

    public Resourced getResources(){
        return mContext.getResources()
    }

    //... all other Methods are implementing the same AdapterPattern
}

这下明白了吧?原来我们平时经常在Activity中使用的this.getResources().***是在这个地方被实现的!

以上摘自:http://stackoverflow.com/questions/9004739/which-class-is-implementing-contextwrappers-methods-in-android

最后,如果需要使用Context的时候,但是这时候没有Context怎么办?比如不在Activity类中。参考前面

You can get the context by invoking getApplicationContext()getContext(),getBaseContext() or this (when in the activity class).

 

 

 

猜你喜欢

转载自michaelye1988.iteye.com/blog/1680133