Volley ImageLoader isCached方法总是返回false

时间:2014-01-15 06:50:07

标签: android android-volley

我正在使用Volley ImageLoader从URI下载图像。

这是我的实施

BitmapLruCache.java

public class BitmapLruCache extends LruCache<String, Bitmap> implements ImageCache {

    public static int getDefaultLruCacheSize() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 6;

        return cacheSize;
    }

    public BitmapLruCache() {
        this(getDefaultLruCacheSize());
    }

    public BitmapLruCache(int sizeInKiloBytes) {
        super(sizeInKiloBytes);
    }

    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight() / 1024;
    }

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

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

VolleyHelper.java

public class VolleyHelper {

    private static final int MAX_IMAGE_CACHE_ENTIRES  = 100;
    private static RequestQueue mRequestQueue;
    private static ImageLoader mImageLoader;

    private VolleyHelper() {
    }

    public static void init(Context context) {
        mRequestQueue = Volley.newRequestQueue(context);
        mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(MAX_IMAGE_CACHE_ENTIRES));
    }

    public static RequestQueue getRequestQueue() {
        if (mRequestQueue != null) {
            return mRequestQueue;
        } else {
            throw new IllegalStateException("RequestQueue not initialized");
        }
    }

    public static ImageLoader getImageLoader() {
        if (mImageLoader != null) {
            return mImageLoader;
        } else {
            throw new IllegalStateException("ImageLoader not initialized");
        }
    }
}

MainActivity.java

ImageLoader mImageLoader = VolleyHelper.getImageLoader();

if (mImageLoader.isCached(url, maxWidth, maxheight)) {
   //always false
}

下载图像并正确显示。但是isCached方法返回false,即使图像已缓存。我不确定参数maxWidthmaxHeight的值应该是多少。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:3)

我浏览了文档,发现了

/**
     * Checks if the item is available in the cache.
     * @param requestUrl The url of the remote image
     * @param maxWidth The maximum width of the returned image.
     * @param maxHeight The maximum height of the returned image.
     * @return True if the item exists in cache, false otherwise.
     */
    public boolean isCached(String requestUrl, int maxWidth, int maxHeight) {
        throwIfNotOnMainThread();

        String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight);
        return mCache.getBitmap(cacheKey) != null;
    }

所以这意味着图像没有正确兑现

文档访问https://android.googlesource.com/platform/frameworks/volley/+/2952b728becbf317f88a627cf17d0b5b6645bb66/src/com/android/volley/toolbox/ImageLoader.java

http://files.evancharlton.com/volley-docs/