您的位置:首页 > 移动开发 > Android开发

Android开发之Context理解

2014-11-10 17:44 351 查看

Android开发之Context理解

Context 本意是上下文,只要是做Android开发的都会发现Context贯穿了整个Android程序,它处处可见,处处可用。
今天,就抽出一点时间来写写Context

Context相关类的继承关系:



从图上我们可以开出,我们的Context只是虚类,但是我们依然可以很明显的发现我们的Application,Activity,Service 都实现了Context,都是Context子类(由此可以看出来Context的核心地位了),这也解释了为什么Context能贯穿整个Android应用
Context字面意思上下文,位于framework package的android.content.Context中,其实该类为LONG型,类似Win32中的Handle句柄,很多方法需要通过 Context才能识别调用者的实例,比如说Toast的第一个参数就是Context。

在android中context可以作很多操作,但是最主要的功能是加载和访问资源。

也可以说 ,Context提供了关于应用环境全局信息的接口
例如Context可以通过以下方式获得信息(非完整)
1.public abstract Context getApplicationContext ()
Return the context of the single, global Application object of the current process.

2.public abstract ApplicationInfo getApplicationInfo ()
Return the full application info for this context's package.

3.public abstract ContentResolver getContentResolver ()
Return a ContentResolver instance for your application's package.

4.public abstract PackageManager getPackageManager ()
Return PackageManager instance to find global package information.

5.public abstract String getPackageName ()
Return the name of this application's package.

6.public abstract Resources getResources ()
Return a Resources instance for your application's package.

7.public abstract SharedPreferences getSharedPreferences (String name, int mode)
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.

8.public final String getString (int resId)
Return a localized string from the application's package's default string table.

9.public abstract Object getSystemService (String name)
Return the handle to a system-level service by name. The class of the returned object varies by the requested name. Currently available names are:


在Android中,一般认为在有两种context,一种是 application context,一种是activity context。

继承关系:





区别联系:

public class MyActivity extends Activity {
public void method() {
mContext = this;    // since Activity extends Context
mContext = getApplicationContext();
mContext = getBaseContext();
}
}


this 是Activity 的实例,扩展了Context,其生命周期是Activity 创建到销毁
getApplicationContext() 返回应用的上下文,生命周期是整个应用,应用摧毁它才摧毁

Activity.this的context 返回当前activity的上下文,属于activity ,activity 摧毁他就摧毁

getBaseContext() 返回由构造函数指定或setBaseContext()设置的上下文,SDK文档很少,不推荐使用

搞清楚了生命周期就会在使用过程中犯错误,比如有一个全局的数据操作类用到了context,这个时候就要用到getApplicationContext 而不是用ACtivity,这就保证了数据库的操作与activity无关(不会一直引用Activity的资源,防止内存泄漏)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: