跟着经典一起学今日值得看给人力量的文字

Android 常用的Context详解

2016-09-03  本文已影响943人  KaelQ

1.Context概述

简单的说:Context负责Activity,Service,Intent,资源,Package和权限。

2.Context家族关系

3.Context使用

4.Context内存泄露问题

public class MyCustomResource {
    //静态变量drawable
    private static Drawable drawable;
    private View view;
    public MyCustomResource(Context context) {
        Resources resources = context.getResources();
        drawable = resources.getDrawable(R.drawable.ic_launcher);
        view = new View(context);
        view.setBackgroundDrawable(drawable);
    }
}
public void setBackgroundDrawable(Drawable background) {
         ..........
         /**此处的this就是当前View对象,而View对象又是有Context对象获得
         因此,变量background持有View对象的引用,View持有Context的引用,
         所有background间接持有Context对象的引用了*/
         background.setCallback(this);
         .......
    }

这时候想要销毁原来的Activity时,发现静态对象Drawable间接持有Context对象的引用,导致Activity的内存无法完全释放内存,这时候就造成了内存泄露。
因此,Android系统在在3.0版本之后修改了setBackgroundDrawable内部方法中的 background.setCallback(this);方法,里面的实现使用了弱引用来持有View对象的引用,从而避免了内存泄漏隐患。所以,以后代码中避免使用静态资源,或者使用弱引用来解决相应的问题也是可以的。

public class CustomManager {
    private static CustomManager sInstance;
    public static CustomManager getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new CustomManager(context);
        }
        return sInstance;
    }
    private Context mContext;
    private CustomManager(Context context) {
        mContext = context;
    }
}

这样单例,有内存泄露的隐患,如果是在Activity中创建这个单例的话,传入的context为Activity的context,如果想要销毁Activity,但是单例的生命周期是整个APP,导致Activity的内存释放不完全。
所以需要修改成如下:

public class CustomManager {
    private static CustomManager sInstance;
    public static CustomManager getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new CustomManager(context.getApplicationContext());
        }
        return sInstance;
    }
    private Context mContext;
    private CustomManager(Context context) {
        mContext = context;
    }
}

将context改为整个Application的Context,这时候单例与Activity就无关了,Activity释放的时候就不会出现内存泄露的问题了。

根据生命周期选择适合的Context类型。

上一篇 下一篇

猜你喜欢

热点阅读