管理Bitmap内存

原文地址:https://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inBitmap
代码下载地址:http://download.youkuaiyun.com/detail/liumeng123321/9758377
除了在缓存Bitmaps中描述的步骤,这里将会介绍一些具体的方法来进行垃圾回收和bitmap重用。这个策略依赖于Android版本。BitmapFun 项目展示了如何针对不同的Android版本,高效的处理Bitmap。
在进行课程之前,先来看一下Android管理Bitmap内存的演进。
.在Android2.2及以下,当进行垃圾回收的时候,app的线程会暂停,这会导致一些操作的延迟,使性能下降,例如我们看到的卡顿问题。Android2.3加入了CONCURRENT垃圾回收(并行GC),位图不再引用后,内存将很快被回收(会很快就回收软引用和弱引用对象)。
.在Android2.3.3及以下,bitmap的像素数据存储在native内存。它与位图本身是分开的,位图存储在Dalvik堆。native内存中的像素不能以一种可预见的方式释放(内存不受虚拟机管理,必须手动调用Recycle方法释放bitmap内存),会导致内存溢出。Android3.0以后,像素数据存储在Davlik堆,所以Bitmap内存由虚拟机管理。

下面的章节描述不同Android版本如何优化bitmap内存管理。
Android2.3.3以及以下版本:
Android2.3.3(API Level 10)以及以下,推荐使用recycle()方法,如果app中有大量的bitmap需要展示,可能会出现OutOfMemoryError错误,recycle()方法可以使app尽可能迅速的回收内存。只有确定bitmap不再使用的时候,再调用recycle,如果调用了recycle()之后,再进行绘制,会得到一个错误:“Canvas: trying to use a recycled bitmap”。
下面的代码片段展示了如何使用recycle()。

private int mCacheRefCount = 0;
private int mDisplayRefCount = 0;
...
// 通知drawable展示的状态已经改变
// 保持一个计数来确定何时可不再显示
public void setIsDisplayed(boolean isDisplayed) {
    synchronized (this) {
        if (isDisplayed) {
            mDisplayRefCount++;
            mHasBeenDisplayed = true;
        } else {
            mDisplayRefCount--;
        }
    }
    // 检查recycle()是否可以被调用.
    checkState();
}

// 通知drawable缓存的状态已经改变
// 保持一个计数来确定何时可不再被缓存。
public void setIsCached(boolean isCached) {
    synchronized (this) {
        if (isCached) {
            mCacheRefCount++;
        } else {
            mCacheRefCount--;
        }
    }
    //检查recycle()是否可以被调用.
    checkState();
}

private synchronized void checkState() {
    // 如果缓存和展示的计数为0, drawable已经被展示了,可以调用recycle()
    if (mCacheRefCount <= 0 && mDisplayRefCount <= 0 && mHasBeenDisplayed
            && hasValidBitmap()) {
        getBitmap().recycle();
    }
}

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

Android3.0及以上版本:
Android 3.0(API level 10)引入了BitmapFactory.Options.inBitmap 字段。如果这个选项被设置了,解码加载内容时将尝试重用现有位图,这意味着bitmap的内存将被重用,从而提高了性能,并删除了内存分配。在使用inBitmap的时候会有一些限制,Android4.4(API level 19)以前,重复使用的位图必须与源内容的大小相同。
下面的代码片段展示了如何重用存在的bitmap。

Set<SoftReference<Bitmap>> mReusableBitmaps;
private LruCache<String, BitmapDrawable> mMemoryCache;

// 如果运行在3.0及以上,创建一个同步的HashSet,用来保存可重复使用的位图
// synchronized HashSet of references to reusable bitmaps.
if (Utils.hasHoneycomb()) {
    mReusableBitmaps =
            Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
}

mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) {

    // 移除不需要缓存的实体
    @Override
    protected void entryRemoved(boolean evicted, String key,
            BitmapDrawable oldValue, BitmapDrawable newValue) {
        if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
            // 移除的实体是回收的drawable, 所以标志为已经移除

            ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
        } else {
            // 如果要移除的是标准的BitmapDrawable,
            if (Utils.hasHoneycomb()) {
                // 将bitmap保存到hashset里。
                mReusableBitmaps.add
                        (new SoftReference<Bitmap>(oldValue.getBitmap()));
            }
        }
    }
....
}

使用存在的bitmap,在运行的app中,检测是否有存在的bitmap可以重用

public static Bitmap decodeSampledBitmapFromFile(String filename,
        int reqWidth, int reqHeight, ImageCache cache) {

    final BitmapFactory.Options options = new BitmapFactory.Options();
    ...
    BitmapFactory.decodeFile(filename, options);
    ...

    // If we're running on Honeycomb or newer, try to use inBitmap.
    if (Utils.hasHoneycomb()) {
        addInBitmapOptions(options, cache);
    }
    ...
    return BitmapFactory.decodeFile(filename, options);
}

下面是addInBitmapOptions() 方法的代码实现。这个方法的作用是查找存在的bitmap,并将值赋给inBitmap。

private static void addInBitmapOptions(BitmapFactory.Options options,
        ImageCache cache) {
    // 可变的bitmap,inBitmap才会起作用, 所以将inMutable 设为true,这样会返回可变的(mutable)bitmap。

    options.inMutable = true;

    if (cache != null) {
        // 查找可以使用的bitmap.
        Bitmap inBitmap = cache.getBitmapFromReusableSet(options);

        if (inBitmap != null) {
            // 如果不为null,给inBitmap赋值
            options.inBitmap = inBitmap;
        }
    }
}

// 查找可重用的bitmap
protected Bitmap getBitmapFromReusableSet(BitmapFactory.Options options) {
        Bitmap bitmap = null;

    if (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) {
        synchronized (mReusableBitmaps) {
            final Iterator<SoftReference<Bitmap>> iterator
                    = mReusableBitmaps.iterator();
            Bitmap item;

            while (iterator.hasNext()) {
                item = iterator.next().get();

                if (null != item && item.isMutable()) {
                    // Check to see it the item can be used for inBitmap.
                    if (canUseForInBitmap(item, options)) {
                        bitmap = item;

                        // Remove from reusable set so it can't be used again.
                        iterator.remove();
                        break;
                    }
                } else {
                    // Remove from the set if the reference has been cleared.
                    iterator.remove();
                }
            }
        }
    }
    return bitmap;
}

最后确定图片尺寸是否满足重用的要求。

static boolean canUseForInBitmap(
        Bitmap candidate, BitmapFactory.Options targetOptions) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // 4.4以后,如果新的bitmap内容的大小,如果小于可重用的bitmap大小,就可以实现重用。
        int width = targetOptions.outWidth / targetOptions.inSampleSize;
        int height = targetOptions.outHeight / targetOptions.inSampleSize;
        int byteCount = width * height * getBytesPerPixel(candidate.getConfig());
        return byteCount <= candidate.getAllocationByteCount();
    }

    // On earlier versions, the dimensions must match exactly and the inSampleSize must be 1
    return candidate.getWidth() == targetOptions.outWidth
            && candidate.getHeight() == targetOptions.outHeight
            && targetOptions.inSampleSize == 1;
}

/**
 * A helper function to return the byte usage per pixel of a bitmap based on its configuration.
 */
static int getBytesPerPixel(Config config) {
    if (config == Config.ARGB_8888) {
        return 4;
    } else if (config == Config.RGB_565) {
        return 2;
    } else if (config == Config.ARGB_4444) {
        return 2;
    } else if (config == Config.ALPHA_8) {
        return 1;
    }
    return 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值