Android使用RecyclerView时如何正确回收位图?

问题描述 投票:0回答:1

正如google所说,当位图在Android 3.0以下不使用时,我们必须手动调用Bitmap.recycle(),因为内存保留在本机堆中。

因此我们可以对 Bitmap 进行引用计数,并在使用 ListView 时检查是否需要在 ImageView 的 onDetachedFromWindow() 中回收位图。这是来自 Google 演示项目 Bitmapfun(ImageFetcher) 的解决方案。

但是在使用RecyclerView时,convertview经常会发生detach和attach的情况。 onDetachedFromWindow() 可能会回收位图,因此当它再次附加到父级时,位图被回收。

如何处理这个问题? Android 3.0以下使用RecyclerView时回收位图的正确方法是什么?

这是Googls的Demo BitmapFun(ImageFetcher)的解决方案——扩展ImageView:

@Override
protected void onDetachedFromWindow() {
    // This has been detached from Window, so clear the drawable
    setImageDrawable(null);

    super.onDetachedFromWindow();
}

@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);
}

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);
        }
    }
}

当从内存缓存中删除时,也在 LruCache 中:

            @Override
            protected void entryRemoved(boolean evicted, String key,
                    BitmapDrawable oldValue, BitmapDrawable newValue) {
                if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
                    // The removed entry is a recycling drawable, so notify it
                    // that it has been removed from the memory cache
                    ((RecyclingBitmapDrawable) oldValue).setIsCached(false);

RecyclingBitmapDrawable 是:

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()) {
        if (BuildConfig.DEBUG) {
            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();
}

}

重要的一点是在ImageView的onDetachedFromWindow中:setImageDrawable(null)表示清除drawable,它可能会使当前drawble的ref count = 0并回收它!该解决方案在使用 ListView 时效果很好,因为 onDetachedFromWindow 仅在 ListView 的根 Activity 被销毁时才会发生。

但是使用Recycling就不一样了,这个Reusing ConvertView的机制和ListView不一样。 ImageView可能经常分离,现在不是回收Bitmap的正确时机!

android listview bitmap android-recyclerview recycle
1个回答
0
投票

您可以使用 glide 来实现这一点。 Glide 会高效地加载图片,您可以在需要时请求它清除资源。

为此,您必须使用 recyclerview 适配器的

onViewRecycled()
方法。您将使用像这样的
clear()
方法来清除资源,

override fun onViewRecycled(holder: VHCustom) {
        super.onViewRecycled(holder)
        Glide.with(ctx).clear(holder.imageView)
    }
© www.soinside.com 2019 - 2024. All rights reserved.