首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

关于Context的懂得

2012-10-05 
关于Context的理解Context?翻译成中文大概是:“上下文,背景”的意思。这是一个抽象类,这个类的具体左右是什么

关于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);//闹钟相关
    getApplicationContext().getContentResolver().query(uri, ...);

    ?

    ?

    主要的作用有3个:

    1.创建对象

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

    3.调用系统组件

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

    ?

    java.lang.Object????android.content.Context关于Context的懂得Known Direct Subclasses关于Context的懂得Known Indirect Subclassespublic 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).

    ?

    ?

    ?

    ?

    ?

    ?

热点排行