除了“缓存位图”中描述的步骤以外,还有一些事情可以用于促进垃圾回收和位图重用,推荐的策略取决于你的android目标版本。下面的BitmapFun实例应用包含一个类,用于展示在不同的android版本下如何设计应用使其更加高效的运行。
作为这一节的基础,下面是关于改进以后的位图内存管理的的相关知识
在android2.2之前,垃圾回收事件发生的时候,应用线程会停止,这会导致操作延迟。android2.3添加了并发的垃圾回收处理,这就意味着位图不在被应用是会被立刻回收。
在android2.3.3之前,对于像素数据的支持保存在本地内存中。这与位图本身是分离的,位图本身存在于dalvik堆中,本地内存中的像素数据会以一种无法预知的方式被释放,可能会导致应用短时内耗尽内存而崩溃。从android3.0开始,像素数据也和其关联位图一起存储于dalvik堆中。
下面将讲述如何在不同的android版本中优化位图内存管理。
Android2.3.3之前管理内存
在android2.3.3之前,推荐使用recycle()。如果你要在应用中展示大量的位图数据,你可能会遇到内存泄露问题。recycle()方法允许app立刻回收内存。
如果你已经确定位图不会再使用,则可以简单调用recycle()方法即可。如果你调用了recycle()方法,再试图绘制位图,则会出现“Canvas: try to use a recycled bitmap”
下面代码片段给出了一个调用recycle()的例子,通过使用引用计数(参数中的mDisplayRefCount和mCacheRefCount)追踪当前位图是正在被展示还是存在于内存中。当满足下列条件时,代码会回收位图。
mDisplayRefCache和mCacheRefCache均为0.
位图不为null,并且没有被recycle()回收.
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之后的内存管理
Android3.0介绍了BitmapFactory.Options.inBitmap属性,如果这个属性被设置,那么携带Options对象的解码方法会在加载内容时试图重用一个现有的位图。这就意味着位图的内存被重用,从而提高可操作性,移除内存分配和解除分配。不过,使用inBitmap有一些限制。特别的,在android4.4中,只有相同尺寸的bitma可以被重用。(可以查看inBitmap文档获取更多详情)
保存位图以备后续使用
下面的代码片段示范了如何在实例应用中保存一个现有的位图,以备后续使用。当一个应用在android3.0以上的版本中运行时,位图会从LruCache中分离,一个对位图的弱引用会被放置在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())); } } } .... }
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的值。注意,只有存在这样一个合适的匹配值时才会将这个值作为inBitmap的值(代码不应假设存在这样的匹配项)。
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) { // 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的尺寸条件。
static boolean canUseForInBitmap( Bitmap candidate, BitmapFactory.Options targetOptions) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // From Android 4.4 (KitKat) onward we can re-use if the byte size of // the new bitmap is smaller than the reusable bitmap candidate // allocation byte count. 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; }