-->

什么时候应该使用LRUCache回收位图?什么时候应该使用LRUCache回收位图?(When sh

2019-05-14 12:18发布

我使用的是LRUCache缓存被存储在文件系统上的位图。 我建立了基于这里的例子缓存: http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html

问题是,我看到的内存溢出崩溃经常同时使用的应用程序。 我认为,当LRUCache逐出的图像以腾出空间给一个又一个,内存不被释放。

我加入到Bitmap.recycle()的图像被逐出时呼叫:

  // use 1/8 of the available memory for this memory cache
    final int cacheSize = 1024 * 1024 * memClass / 8;
                mImageCache = new LruCache<String, Bitmap>(cacheSize) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    return bitmap.getByteCount();
                }

                @Override
                protected void entryRemoved(boolean evicted, String key, Bitmap oldBitmap, Bitmap newBitmap) {
                    oldBitmap.recycle();
                    oldBitmap = null;
                }
            };

这修复了崩溃,但它也导致图像有时不能在应用程序(只是一个黑色的空间,图像应该是)出现。 发生我看到我的logcat此消息的任何时间: Cannot generate texture from bitmap

快速谷歌搜索发现,这是发生,因为这是显示图像已被回收。

那么,什么是发生在这里? 为什么在LRUCache还是回收的图像,如果我只回收他们,他们已经被删除后? 什么是用于实现高速缓存的选择吗? Android的文档明确指出LRUCache是​​要走的路,但他们没有提到需要回收位图或怎么做。

解决:如果它有用给其他人,由接受的答案建议解决这个问题是不能做什么,我在做上面的代码示例(不回收的位图entryRemoved()调用)。

取而代之的是,当你与一个ImageView的(如完成onPause()一个活动,或者当一个视图中的适配器再生纸)检查,如果该位图是仍在缓存中(我加了isImageInCache()方法,以我的缓存类),如果不是的话,那么回收的位图。 否则,不要管它。 这个固定我的OutOfMemory异常,并阻止其仍在使用回收的位图。

Answer 1:

我认为,当LRUCache逐出的图像以腾出空间给一个又一个,内存不被释放。

这不会是,直到Bitmap被回收或垃圾收集。

快速谷歌搜索发现,这是发生,因为这是显示图像已被回收。

这就是为什么你不应该回收存在。

为什么在LRUCache还是回收的图像,如果我只回收他们,他们已经被删除后?

据推测,他们是不是在LRUCache 。 他们是在一个ImageView或仍在使用别的Bitmap

什么是用于实现高速缓存的选择吗?

为了讨论的方便,我们假设你正在使用的Bitmap中的对象ImageView小部件,如在行ListView

如果你是一个做Bitmap (例如,排在ListView循环),你检查,看它是否仍然在缓存中。 如果是,你不要管它。 如果不是,你recycle()它。

缓存是简单地让你知道哪些Bitmap对象是值得持有到。 缓存有没有,如果知道的方式Bitmap仍然在某个地方使用。

顺便说一句,如果你对API等级11+,可以考虑使用inBitmapOutOMemoryErrors当分配不能满足被触发。 上次我检查,Android不具备压缩垃圾收集器,这样你就可以得到一个OutOfMemoryError因碎片(要分配比最大的单一可用块更大的东西)。



Answer 2:

面对相同的,感谢@CommonsWare的讨论。 在这里张贴了完整的解决方案,以便它可以帮助更多的人来这里同样的问题。 编辑和注释的欢迎。 干杯

 When should I recycle a bitmap using LRUCache?
  • 正是当你的位图既不是在缓存中,也没有任何的ImageView得到引用。

  • 为了保持位图的引用计数,我们必须扩展BitmapDrawable类,并添加引用属性给他们。

  • 这个机器人样品有它的答案完全相同。 DisplayingBitmaps.zip

我们将获取到的细节和下面的代码。

(don't recycle the bitmaps in the entryRemoved() call).

不完全是。

  • 在entryRemoved委托检查是否位图仍然从任何ImageView的引用。 如果不。 回收它有本身。

  • 而这是在接受的答案,当视图即将得到重用或得到提到反之亦然倾倒检查其位图(前位,如果观点得到重用)是在缓存中。 如果是有息事宁人其他回收。

  • 这里的关键是我们需要检查在两个地方,我们是否可以回收位图或没有。

我将解释我在哪里使用LruCache举行位图对我来说我的具体情况。 而在ListView中显示它们。 并呼吁位图的循环时,有不再使用。

上述样品的RecyclingBitmapDrawable.java和RecyclingImageView.java是我们在这里所需要的核心部分。 他们是美丽的搬运东西。 他们setIsCached和setIsDisplayed方法在做什么,我们需要的。

代码可以在上面提到的样品的链接被发现。 但也发布文件的回答底部的完整代码的情况下,在未来的链路出现故障或发生变化。 难道覆盖setImageResource还检查以前的位图的状态的一个小的修改。

---这里有云的代码为你---

所以,你的LruCache经理应该是这个样子。

LruCacheManager.java

package com.example.cache;

import android.os.Build;
import android.support.v4.util.LruCache;

public class LruCacheManager {

    private LruCache<String, RecyclingBitmapDrawable> mMemoryCache;

    private static LruCacheManager instance;

    public static LruCacheManager getInstance() {
        if(instance == null) {
            instance = new LruCacheManager();
            instance.init();
        } 

        return instance;
    }

    private void init() {

        // We are declaring a cache of 6Mb for our use.
        // You need to calculate this on the basis of your need 
        mMemoryCache = new LruCache<String, RecyclingBitmapDrawable>(6 * 1024 * 1024) {
            @Override
            protected int sizeOf(String key, RecyclingBitmapDrawable bitmapDrawable) {
                // The cache size will be measured in kilobytes rather than
                // number of items.
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
                    return bitmapDrawable.getBitmap().getByteCount() ;
                } else {
                    return bitmapDrawable.getBitmap().getRowBytes() * bitmapDrawable.getBitmap().getHeight();
                }
            }

            @Override
            protected void entryRemoved(boolean evicted, String key, RecyclingBitmapDrawable oldValue, RecyclingBitmapDrawable newValue) {
                super.entryRemoved(evicted, key, oldValue, newValue);
                oldValue.setIsCached(false);
            }
        };

    }

    public void addBitmapToMemoryCache(String key, RecyclingBitmapDrawable bitmapDrawable) {
        if (getBitmapFromMemCache(key) == null) {
            // The removed entry is a recycling drawable, so notify it
            // that it has been added into the memory cache
            bitmapDrawable.setIsCached(true);
            mMemoryCache.put(key, bitmapDrawable);
        }
    }

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

    public void clear() {
        mMemoryCache.evictAll();
    }
}


和你的getView(的ListView / GridView的适配器)看起来应该像正常如常。 当你在使用ImageView的方法setImageDrawable设置一个新的形象。 它的内部检查以前的位图的引用计数,并在内部如果不叫回收它在lrucache。

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        RecyclingImageView imageView;
        if (convertView == null) { // if it's not recycled, initialize some attributes
            imageView = new RecyclingImageView(getActivity());
            imageView.setLayoutParams(new GridView.LayoutParams(
                    GridView.LayoutParams.WRAP_CONTENT,
                    GridView.LayoutParams.WRAP_CONTENT));
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setPadding(5, 5, 5, 5);

        } else {
            imageView = (RecyclingImageView) convertView;
        }

        MyDataObject dataItem = (MyDataObject) getItem(position);
        RecyclingBitmapDrawable  image = lruCacheManager.getBitmapFromMemCache(dataItem.getId());

        if(image != null) {
            // This internally is checking reference count on previous bitmap it used.
            imageView.setImageDrawable(image);
        } else {
            // You have to implement this method as per your code structure.
            // But it basically doing is preparing bitmap in the background
            // and adding that to LruCache.
            // Also it is setting the empty view till bitmap gets loaded.
            // once loaded it just need to call notifyDataSetChanged of adapter. 
            loadImage(dataItem.getId(), R.drawable.empty_view);
        }

        return imageView;

    }

这里是你的RecyclingImageView.java

/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.cache;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;


/**
 * Sub-class of ImageView which automatically notifies the drawable when it is
 * being displayed.
 */
public class RecyclingImageView extends ImageView {

    public RecyclingImageView(Context context) {
        super(context);
    }

    public RecyclingImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * @see android.widget.ImageView#onDetachedFromWindow()
     */
    @Override
    protected void onDetachedFromWindow() {
        // This has been detached from Window, so clear the drawable
        setImageDrawable(null);

        super.onDetachedFromWindow();
    }

    /**
     * @see android.widget.ImageView#setImageDrawable(android.graphics.drawable.Drawable)
     */
    @Override
    public void setImageDrawable(Drawable drawable) {
        // Keep hold of previous Drawable
        final Drawable previousDrawable = getDrawable();

        // Call super to set new Drawable
        super.setImageDrawable(drawable);

        // Notify new Drawable that it is being displayed
        notifyDrawable(drawable, true);

        // Notify old Drawable so it is no longer being displayed
        notifyDrawable(previousDrawable, false);
    }

    /**
     * @see android.widget.ImageView#setImageResource(android.graphics.drawable.Drawable)
     */
    @Override
    public void setImageResource(int resId) {
        // Keep hold of previous Drawable
        final Drawable previousDrawable = getDrawable();

        // Call super to set new Drawable
        super.setImageResource(resId);

        // Notify old Drawable so it is no longer being displayed
        notifyDrawable(previousDrawable, false);
    }


    /**
     * Notifies the drawable that it's displayed state has changed.
     *
     * @param drawable
     * @param isDisplayed
     */
    private static void notifyDrawable(Drawable drawable, final boolean isDisplayed) {
        if (drawable instanceof RecyclingBitmapDrawable) {
            // The drawable is a CountingBitmapDrawable, so notify it
            ((RecyclingBitmapDrawable) drawable).setIsDisplayed(isDisplayed);
        } else if (drawable instanceof LayerDrawable) {
            // The drawable is a LayerDrawable, so recurse on each layer
            LayerDrawable layerDrawable = (LayerDrawable) drawable;
            for (int i = 0, z = layerDrawable.getNumberOfLayers(); i < z; i++) {
                notifyDrawable(layerDrawable.getDrawable(i), isDisplayed);
            }
        }
    }

}

这里是你的RecyclingBitmapDrawable.java

/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.cache;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;

import android.util.Log;

/**
 * A BitmapDrawable that keeps track of whether it is being displayed or cached.
 * When the drawable is no longer being displayed or cached,
 * {@link android.graphics.Bitmap#recycle() recycle()} will be called on this drawable's bitmap.
 */
public class RecyclingBitmapDrawable extends BitmapDrawable {

    static final String TAG = "CountingBitmapDrawable";

    private int mCacheRefCount = 0;
    private int mDisplayRefCount = 0;

    private boolean mHasBeenDisplayed;

    public RecyclingBitmapDrawable(Resources res, Bitmap bitmap) {
        super(res, bitmap);
    }

    /**
     * Notify the drawable that the displayed state has changed. Internally a
     * count is kept so that the drawable knows when it is no longer being
     * displayed.
     *
     * @param isDisplayed - Whether the drawable is being displayed or not
     */
    public void setIsDisplayed(boolean isDisplayed) {
        //BEGIN_INCLUDE(set_is_displayed)
        synchronized (this) {
            if (isDisplayed) {
                mDisplayRefCount++;
                mHasBeenDisplayed = true;
            } else {
                mDisplayRefCount--;
            }
        }

        // Check to see if recycle() can be called
        checkState();
        //END_INCLUDE(set_is_displayed)
    }

    /**
     * Notify the drawable that the cache state has changed. Internally a count
     * is kept so that the drawable knows when it is no longer being cached.
     *
     * @param isCached - Whether the drawable is being cached or not
     */
    public void setIsCached(boolean isCached) {
        //BEGIN_INCLUDE(set_is_cached)
        synchronized (this) {
            if (isCached) {
                mCacheRefCount++;
            } else {
                mCacheRefCount--;
            }
        }

        // Check to see if recycle() can be called
        checkState();
        //END_INCLUDE(set_is_cached)
    }

    private synchronized void checkState() {
        //BEGIN_INCLUDE(check_state)
        // If the drawable cache and display ref counts = 0, and this drawable
        // has been displayed, then recycle
        if (mCacheRefCount <= 0 && mDisplayRefCount <= 0 && mHasBeenDisplayed
                && hasValidBitmap()) {

            Log.d(TAG, "No longer being used or cached so recycling. "
                        + toString());

        getBitmap().recycle();
    }
        //END_INCLUDE(check_state)
    }

    private synchronized boolean hasValidBitmap() {
        Bitmap bitmap = getBitmap();
        return bitmap != null && !bitmap.isRecycled();
    }

}


文章来源: When should I recycle a bitmap using LRUCache?