Managing Bitmap Memory [管理Bitmap内存]

Managing Bitmap Memory [管理Bitmap内存]


除了在CachingBitmaps中描述的几个措施之外,你还可以做一些明确的事情来促进垃圾回收和位图的重用。Android目标版本决定了我们将推荐使用什么策略。BitmapFun这个示例app包含了这样一个类,这个类向你展示了怎样设计你的app,才能在android的不同版本之间高效率的工作。
 
为了给这节课打好基础, 先来看看Android关于Bitmap内存管理的进化:
  • 在Android2.2或更低的版本中,当发生垃圾回收时,你应用的线程都会暂停执行。这会导致延迟,降低程序性能。Android2.3增加了并发的垃圾回收机制,这意味着当图片对象不再被引用时所占用的内存空间立即就会被回收。
  •   在Android2.3.3或更低版本中,图片的像素数据是存储在本地内存(JVM 用于其内部操作的内存)中的,它和Bitmap对象本身是分开来的,Bitmap对象本身是存储在Java虚拟机堆内存中。存储在本地内存中的像素数据的释放是不可预知的,这样就有可能导致应用短暂的超过其内存限制而崩溃。Android3.0之后,Bitmap像素数据和它本身都存储在Java虚拟机的堆内存中。
 下面的部分介绍了对不同的Android版本中的Bitmap内存管理的优化。

Manage Memory on Android 2.3.3 and Lower [Android2.3或更低版本中对Bitmap内存的管理]


    在Android2.3或更低版本中,推荐使用recycle()方法。如果在你的应用中需要显示大量的图片,那么你的应用很有可能出现OutOfMemoryError 的错误。调用 recycle() 方法能让应用尽可能快的回收内存资源。     

警告:只有当你确定不会再使用这张Bitmap图片时才应该调用recycle()方法。如果你调用recycle(),随后就尝试去画这张图,你将会得到"Canvas: trying to use a recycled bitmap" 的错误 。

下面的程序片段是给出了一个调用recycle() 方法的示例,它使用引用计数(mDisplayRefCount and mCacheRefCount)来追踪一张Bitmap是正在被显示还是存储在内存缓存中,代码回收Bitmap需要符合下面的几个条件:

  • mDisplayRefCount 和 mCacheRefCount  的引用计数都为0
  • Bitmap对象不为null,并且还没有被回收 

private int mCacheRefCount = 0;
private int mDisplayRefCount = 0;
...
// Notify the drawable that the displayed state has changed.
// Keep a count to determine when the drawable is no longer displayed.
public void setIsDisplayed(boolean isDisplayed) {
    synchronized (this) {
        if (isDisplayed) {
            mDisplayRefCount++;
            mHasBeenDisplayed = true;
        } else {
            mDisplayRefCount--;
        }
    }
    // Check to see if recycle() can be called.
    checkState();
}

// Notify the drawable that the cache state has changed.
// Keep a count to determine when the drawable is no longer being cached.
public void setIsCached(boolean isCached) {
    synchronized (this) {
        if (isCached) {
            mCacheRefCount++;
        } else {
            mCacheRefCount--;
        }
    }
    // Check to see if recycle() can be called.
    checkState();
}

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

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

Manage Memory on Android 3.0 and Higher[Android3.0或更高版本中对Bitmap内存的管理]


   在Android3.0中为我们引进了BitmapFactory.Options.inBitmap 属性。 如果设置了这个选项,那么在加载图片的时候,使用了Options对象作为参数的decode方法会试图重用已存在的Bitmap。这意味着Bitmap的内存资源被重用了,从而使得程序性能得到提高,并且省去了这份内存的分配和回收工作。下面是使用inBitmap 属性的一些说明和注意点:
  • 要进行重用的Bitmap的大小必须要跟源图片大小一致(确保两者使用的内存大小一样),而且图片必须是PNG或JPEG格式(可以是资源,也可以是二进制流数据).
  • 如果源图片设置了inPreferredConfig 配置项,那么要进行重用的Bitmap也设置此项.
  • 你应该总是使用decode方法返回的Bitmap,因为你不能保证重用的Bitmap是否可靠(比如,上面提到的大小有可能不匹配)

Save a bitmap for later use[保存一张Bitmap供以后使用]

  下面的程序片段演示了 在示例应用中一个已存在的bitmap是如何存储以备之后使用的。
当应用运行在Android3.0或更高版本上,当一张Bitmap从LruCache退出时,Bitmap的软引用会被保存在一个HashSet中 ,可能稍后会被inBitmap 使用。
HashSet<SoftReference<Bitmap>> mReusableBitmaps;
private LruCache<String, BitmapDrawable> mMemoryCache;

// If you're running on Honeycomb or newer, create
// a HashSet of references to reusable bitmaps.
if (Utils.hasHoneycomb()) {
    mReusableBitmaps = new HashSet<SoftReference<Bitmap>>();
}

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

    //Notify the removed entry that is no longer being cached.
    @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);
        } else {
            // The removed entry is a standard BitmapDrawable.
            if (Utils.hasHoneycomb()) {
                // We're running on Honeycomb or later, so add the bitmap
                // to a SoftReference set for possible use with inBitmap later.
                mReusableBitmaps.add
                        (new SoftReference<Bitmap>(oldValue.getBitmap()));
            }
        }
    }
....
}

Use an existing bitmap [使用已经存在的Bitmap]

在运行的app中,decoder 方法会去检查是否有一张已经存在的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() 方法在下面定义了。它会去查找inBitmap是否设置了一张已经存在的Bitmap ,注意这个方法只有在它找到一个合适的匹配图片才会设置inBitmap的值(你永远都不要去假设相匹配的图片一定找得到)。

       ImageCache cache) {
    // inBitmap only works with mutable bitmaps, so force the decoder to
    // return mutable bitmaps.
    options.inMutable = true;

    if (cache != null) {
        // Try to find a bitmap to use for inBitmap.
        Bitmap inBitmap = cache.getBitmapFromReusableSet(options);

        if (inBitmap != null) {
            // If a suitable bitmap has been found, set it as the value of
            // inBitmap.
            options.inBitmap = inBitmap;
        }
    }
}

// This method iterates through the reusable bitmaps, looking for one 
// to use for inBitmap:
protected Bitmap getBitmapFromReusableSet(BitmapFactory.Options options) {
        Bitmap bitmap = null;

    if (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) {
        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;
}

最后,这个方法用来判断一张候选图片是否满足 inBitmap 用来使用的尺寸标准:

private static boolean canUseForInBitmap(
        Bitmap candidate, BitmapFactory.Options targetOptions) {
    int width = targetOptions.outWidth / targetOptions.inSampleSize;
    int height = targetOptions.outHeight / targetOptions.inSampleSize;

    // Returns true if "candidate" can be used for inBitmap re-use with
    // "targetOptions".
    return candidate.getWidth() == width && candidate.getHeight() == height;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值