很多地方我們需要使用到Context,比如我們自定義一個單例的CustomManager,當我們使用一些系統的服務時,就需要Context參數,這時如果使用Activity或者Service 作爲context,就會容易造成內存泄露。
具體原因請看下面的這個例子:
pubic class CustomManager {
private static CustomManager sInstance;
public static CustomManager getInstance(Context context) {
if (sInstance == null) {
// 這個類擁有了一個靜態的context引用
sInstance = new CustomManager(context);
}
return sInstance;
}
private Context mContext;
private CustomManager(Context context) {
mContext = context;
}
}
當所持有的Context的引用是一個Activity或者Service,系統銷燬它們後,由於CustomManager中有其靜態的引用,所以Activity或者Service所佔用的資源並不會被回收,造成內存泄露。
那麼正確的方法是使用Application的context, 因爲Application的context是單例的,並且它的生命週期屬於整個應用進程。所以上邊的代碼需要改成:
private static CustomManager sInstance;
public static CustomManager getInstance(Context context) {
if (sInstance == null) {
// 這個類擁有了一個靜態的context引用
sInstance = new CustomManager(context.getApplicationContext());
}
return sInstance;
}
private Context mContext;