0

我将 GridView 中的位图缓存到 LruCache。我为此做了经理,见下文:

private LruCache<String, Bitmap> mMemoryCache;

public LruCacheManager(){
    init();
}

private void init(){

    // Get max available VM memory, exceeding this amount will throw an
    // OutOfMemory exception. Stored in kilobytes as LruCache takes an
    // int in its constructor.
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 8;

    //Log.i("ImageCache","cacheSize: " + cacheSize);
    if(mMemoryCache == null){
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in kilobytes rather than
                // number of items.
                // The cache size will be measured in kilobytes rather than
                // number of items.
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
                    return bitmap.getByteCount() ;
                } else {
                    return bitmap.getRowBytes() * bitmap.getHeight();
                }
            }

        };
    }


}

public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
    if (getBitmapFromMemCache(key) == null) {
        Log.i("LruCacheManager","Bitmap is getting added, " + key);
        mMemoryCache.put(key, bitmap);
    }
}

public Bitmap getBitmapFromMemCache(String key) {
    return mMemoryCache.get(key);
}

当我调用addBitmapToMemoryCache()我的 AsyncTask 将位图保存到 MemoryCache 时。

但是当我打电话给getBitmapFromMemoryCache()它时null

//get cached Bitmap
    LruCacheManager imCache = new LruCacheManager();
    String imageKey = categoryNames[position];
    Bitmap cachedBm = imCache.getBitmapFromMemCache(imageKey);

    //Decide whatever use cached image or not
    if (cachedBm != null) {
        Log.i("AdapterGridView","Using cached image, " + imageKey);
        viewHolder.icon.setImageBitmap(cachedBm);
    } else {
        //starts Asynctask to scale pictures and show them, happens off the main thread
        new AsyncTaskImageLoader(viewHolder.icon, imageKey, mContext, imCache, mThumbIds[position]).execute();
    }

这意味着, AsyncTask 被一次又一次地调用。在 AsyncTask 中,我将位图添加到 LruCache。因为返回的Bitmap为null,所以LruCache中没有保存Bitmap。但我不知道为什么。我也在网上搜索,它可能与回收/垃圾收集器有关。

那么如何正确加载缓存的图像?

任何帮助或澄清都是合适的。

编辑:

我在 getView() 方法中的 BaseAdapter 中调用它。我认为这与它有关。第一次,每个图像都被添加到缓存中,但随后,第一张图像被添加了 10 次。

4

1 回答 1

1

首先,我将设置任意内存大小并尝试使用 1 张图像。其余的看起来不错...如果我在下面的内容不起作用,请给我们打印出您的记忆等。您可能没有。

在我的版本中,我通过

  final int maxMemory = (int) (Runtime.getRuntime().maxMemory());

然后将其设置为一个分数(我想我选择了第 8 个)我在返回时执行 /1024 获取大小,我这样做是为了设置内存。因此,如果您拥有您认为拥有的内存的 1/1000,那将是可能的问题。

于 2014-09-03T17:43:26.990 回答