Android开发之Context理解

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的资源,防止内存泄漏)

比如一个activity的onCreate:
protected void onCreate(Bundle state) {
        super.onCreate(state);
 
        TextView label = new TextView(this); //传递context给view control
        label.setText("Leaks are bad");
 
        setContentView(label);
}


把activity context传递给view,意味着view拥有一个指向activity的引用,进而引用activity占有的资源:view hierachy, resource等。
这样如果context发生内存泄露的话,就会泄露很多内存。
这里泄露的意思是gc没有办法回收activity的内存。
 
Leaking an entire activity是很容易的一件事。
 
当屏幕旋转的时候,系统会销毁当前的activity,保存状态信息,再创建一个新的。
 
比如我们写了一个应用程序,它需要加载一个很大的图片,我们不希望每次旋转屏 幕的时候都销毁这个图片,重新加载。实现这个要求的简单想法就是定义一个静态的Drawable,这样Activity 类创建销毁它始终保存在内存中。
实现类似:
public class myactivity extends Activity {
        private static Drawable sBackground;
        protected void onCreate(Bundle state) {
                super.onCreate(state);
 
                TextView label = new TextView(this);
                label.setText("Leaks are bad");
 
                if (sBackground == null) {
                        sBackground = getDrawable(R.drawable.large_bitmap);
                }
        label.setBackgroundDrawable(sBackground);//drawable attached to a view
 
        setContentView(label);
        }
}


这段程序看起来很简单,但是却问题很大。当屏幕旋转的时候会有leak(即gc没法销毁activity)。
我们刚才说过,屏幕旋转的时候系统会销毁当前的activity。但是当drawable和view关联后,drawable保存了view的 reference,即sBackground保存了label的引用,而label保存了activity的引用。既然drawable不能销毁,它所 引用和间接引用的都不能销毁,这样系统就没有办法销毁当前的activity,于是造成了内存泄露。gc对这种类型的内存泄露是无能为力的。
 
避免这种内存泄露的方法是避免activity中的任何对象的生命周期长过activity,避免由于对象对 activity的引用导致activity不能正常被销毁。我们可以使用application context。application context伴随application的一生,与activity的生命周期无关。application context可以通过Context.getApplicationContext或者Activity.getApplication方法获取。
 
避免context相关的内存泄露,记住以下几点:
1. 不要让生命周期长的对象引用activity context,即保证引用activity的对象要与activity本身生命周期是一样的
2. 对于生命周期长的对象,可以使用application context
3. 避免非静态的内部类,尽量使用静态类,避免生命周期问题,注意内部类对外部对象引用导致的生命周期变化


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值