zoukankan      html  css  js  c++  java
  • android: Context引起的内存泄露问题

    错误的使用Context可能会导致内存泄漏,典型的例子就是单例模式时引用不合适的Context。

    public class SingleInstance {
        private static SingleInstance sSingleInstance;
        private Context mContext;
    
        public SingleInstance(Context mContext) {
            this.mContext = mContext;
        }
    
        public static SingleInstance getInstance(Context context){
            if(sSingleInstance==null){
                sSingleInstance=new SingleInstance(context);
            }
            return sSingleInstance;
        }
    }
    如果使用getInstance传入的是Activity或者Service的实例,那么由于在应用退出之前创建的单例对象会一直存在并持有Activity或者Service的引用,回使Activity或者Service无法被垃圾回收从而导致内存泄漏。正确的做法是使用Application Context对象,因为它的生命周期是和应用一致的。
    public class SingleInstance {
        private static SingleInstance sSingleInstance;
        private Context mContext;
    
        public SingleInstance(Context mContext) {
            this.mContext = mContext;
        }
    
        public static SingleInstance getInstance(Context context){
            if(sSingleInstance==null){
                sSingleInstance=new SingleInstance(context.getApplicationContext());//使用Application Context
            }
            return sSingleInstance;
        }
    }
  • 相关阅读:
    归并排序
    msp430的时钟源设计
    插入排序
    msp430F5438A 的中断初步
    算法导论,第一节第二节课总结
    MSP430F5438A的时钟系统
    msp430F5438A 的ADC 研究
    图像处理基本原理(转载)
    C++标准库简介
    C# 接口 抽象类
  • 原文地址:https://www.cnblogs.com/yongdaimi/p/10905991.html
Copyright © 2011-2022 走看看