Android进阶练习 - 高效显示Bitmap(管理Bitmap内存)
2014-03-17 11:13
435 查看
管理Bitmap内存
转载自:http://blog.csdn.net/tu_bingbing/article/details/8773525?reload
除了在前面几篇文章中提到的缓存图片的步骤外,还有一些事情需要做来促进垃圾回收和位图的重用。Android目标版本决定了我们将使用什么策略。
先来看看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() 示例,使用到了引用计数(
mDisplayRefCountand
mCacheRefCount)来追踪一张Bitmap是正在被显示还是存储在内存缓存中,回收Bitmap需要符合以下两个条件
1、
mDisplayRefCountand
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供以后使用
在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())); } } } .... }
使用已经存在的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; }
相关文章推荐
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- 解決Linux下Android开发真机调试设备不被识别问题
- [Android]在代码里运行另一个程序的方法
- [软件咨询]WPS2012正式版已发布 金山Office移动版4.0发布
- Android笔记-Linux Kernel Ftrace (Function Trace)解析
- android USB如何修改VID具体实现
- Android增量升级的方法和原理详细介绍
- Android Mouse实现过程详细笔记
- 深入Android Browser配置管理的详解
- Android Mms之:深入理解对话列表管理
- Oracle索引(B*tree与Bitmap)的学习总结
- Android APP与媒体存储服务的交互
- android 多线程技术应用
- Android之采用execSQL与rawQuery方法完成数据的添删改查操作详解
- Android数据类型之间相互转换系统介绍
- 通过Android trace文件分析死锁ANR实例过程
- Android实现左右滑动效果的方法详解
- Android 各国语言缩写及简称详细介绍