管理Bitmap内存
先来看看Android不同版本对Bitmap管理的进化
在Android2.2或更低的版本中,当出现垃圾回收时,你的应用会暂停执行。这会导致延迟,降低程序性能。Android2.3增加了并行的垃 圾回收机制,这意味着当图片对象不再被引用时所占用的内存空间马上会被回收利用
在Android2.3或更低版本中,图片的像素级数据是存储在本地内存(JVM 用于其内部操作的内存)中的,它和Bitmap对象本身是分开来的,Bitmap对象本身是存储在Java虚拟机堆中。在本地内存中的像素数据的释放是不可预知的,这样就有可能会导致应用短暂的超过内存限制,从而程序崩溃。Android3.0之后,Bitmap像素数据和它本身都存储在Java虚拟机的堆内存中
下面我们来看看在不同的Android版本中如何来对Bitmap内存进行管理
Android2.3或更低版本中对Bitmap内存的管理
在Android2.3或更低版本中,推荐对Bitmap使用
recycle()
方法。如果你在你的一个应用中需要显示大量的图片,那么你的应用非常有可能出现
OutOfMemoryError 错误。调用
recycle()
方法能让应用以尽可能快的回收Bitmap所占用的内存资源。
警告:你应该调用
recycle()
方法的时机是:当你不会再使用这张Bitmap。如果你后续再试图去访问,你将会得到
"Canvas: trying to use a recycled bitmap"
错误
下面的程序片段是调用
recycle() 示例,使用到了引用计数(
mDisplayRefCount
and
mCacheRefCount
)来追踪一张Bitmap是正在被显示还是存储在内存缓存中,回收Bitmap需要符合以下两个条件
1、
mDisplayRefCount
and mCacheRefCount
的引用计数都为0
2、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(); }
Android3.0或更高版本中对Bitmap内存的管理
在Android3.0中为我们介绍了
BitmapFactory.Options.inBitmap 属性。 如果设置了这个属性,那么使用了
Options
对象作为参数的decode方法会试图重用现有的Bitmap来作为方法的返回值。 这意味着Bitmap的内存资源被重用了,从而使得程序性能得到提高,并且消除了这份内存的分配和回收工作。下面是使用
inBitmap 属性的一些说明和注意点
要进行重用的Bitmap的大小必须要跟源图片大小一致(确保两者内存使用大小一样),而且图片必须是PNG或JPEG格式(可以是资源,也可以是二进制流数据)
如果源图片设置了inPreferredConfig 配置项,那么要进行重用的Bitmap也设置此项
你应该一值使用decode方法返回的Bitmap,因为我们不能保证重用的Bitmap是否可靠(比如,上面提到的大小有可能不匹配)
保存一张Bitmap供以后使用
-
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())); } } } .... }
使用已经存在的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 只设置相匹配的图片(你永远都不要去假设相匹配的图片一定找得到),LZ在实际使用中发现需要屏蔽 options.inBitmap != 1 的情况,具体原因不是很明白,这里有一个视频阐述了这个问题
http://www.youtube.com/watch?v=rsQet4nBVi8
-
private static void addInBitmapOptions(BitmapFactory.Options options, 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 && options.inBitmap == 1) { // 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; }