究竟是什么导致静态上下文中的内存泄漏?

时间:2017-09-23 12:17:23

标签: java android memory-leaks singleton android-context

我正在阅读Google Developer's Guide on the Volley Framework并发现他们在代码中使用了这一行:

 private static Context mCtx;

Volley Singleton 的整个代码(来自https://developer.android.com):

public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;

private MySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();

    mImageLoader = new ImageLoader(mRequestQueue,
            new ImageLoader.ImageCache() {
        private final LruCache<String, Bitmap>
                cache = new LruCache<String, Bitmap>(20);

        @Override
        public Bitmap getBitmap(String url) {
            return cache.get(url);
        }

        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            cache.put(url, bitmap);
        }
    });
}

public static synchronized MySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new MySingleton(context);
    }
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}

public ImageLoader getImageLoader() {
    return mImageLoader;
}

直到现在我才知道使用静态Context字段是内存泄漏。但是,我不明白为什么在这里使用这样的东西。

我想知道为什么这不是内存泄漏。 (假设它不是,因为它在教程网站上)

0 个答案:

没有答案