錯誤的使用Context可能會致使內存泄漏,典型的例子就是單例模式時引用不合適的Context。this
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; } }
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; } }