Android中Bitmap缓存池

移动开发 Android
本文介绍了如何使用缓存来提高UI的载入输入和滑动的流畅性。使用内存缓存、使用磁盘缓存、处理配置改变事件等方法将会有效的解决这个问题。

在您的UI中显示单个图片是非常简单的,如果您需要一次显示很多图片就有点复杂了。在很多情况下(例如使用 ListView, GridView 或者 ViewPager控件),显示在屏幕上的图片以及即将显示在屏幕上的图片数量是非常大的(例如在图库中浏览大量图片)。

在这些控件中,当一个子控件不显示的时候,系统会重用该控件来循环显示 以便减少对内存的消耗。同时垃圾回收机制还会释放那些已经载入内存中的Bitmap资源(假设您没有强引用这些Bitmap)。一般来说这样都是不错的,但是在用户来回滑动屏幕的时候,为了保证UI的流畅性和载入图片的效率,您需要避免重复的处理这些需要显示的图片。 使用内存缓存和磁盘缓存可以解决这个问题,使用缓存可以让控件快速的加载已经处理过的图片。

本文介绍如何使用缓存来提高UI的载入输入和滑动的流畅性。

使用内存缓存

内存缓存提高了访问图片的速度,但是要占用不少内存。 LruCache
类(在API 4之前可以使用Support Library 中的类 )特别适合缓存Bitmap, 把最近使用到的
Bitmap对象用强引用保存起来(保存到LinkedHashMap中),当缓存数量达到预定的值的时候,把
不经常使用的对象删除。

注意: 过去,实现内存缓存的常用做法是使用
SoftReference 或者
WeakReference bitmap 缓存,
但是不推荐使用这种方式。从Android 2.3 (API Level 9) 开始,垃圾回收开始强制的回收掉 soft/weak 引用 从而导致这些缓存没有任何效率的提升。
另外,在 Android 3.0 (API Level 11)之前,这些缓存的Bitmap数据保存在底层内存(native memory)中,并且达到预定条件后也不会释放这些对象,从而可能导致
程序超过内存限制并崩溃。

在使用 LruCache 的时候,需要考虑如下一些因素来选择一个合适的缓存数量参数:

  • 程序中还有多少内存可用

  • 同时在屏幕上显示多少图片?要先缓存多少图片用来显示到即将看到的屏幕上?

  • 设备的屏幕尺寸和屏幕密度是多少?超高的屏幕密度(xhdpi 例如 Galaxy Nexus)
    设备显示同样的图片要比低屏幕密度(hdpi 例如 Nexus S)设备需要更多的内存。

  • 图片的尺寸和格式决定了每个图片需要占用多少内存

  • 图片访问的频率如何?一些图片的访问频率要比其他图片高很多?如果是这样的话,您可能需要把这些经常访问的图片放到内存中。

  • 在质量和数量上如何平衡?有些情况下保存大量的低质量的图片是非常有用的,当需要的情况下使用后台线程来加入一个高质量版本的图片。

这里没有万能配方可以适合所有的程序,您需要分析您的使用情况并在指定自己的缓存策略。使用太小的缓存并不能起到应有的效果,而使用太大的缓存会消耗更多
的内存从而有可能导致 java.lang.OutOfMemory 异常或者留下很少的内存供您的程序其他功能使用。

下面是一个使用 LruCache 缓存的示例:

  1. private LruCache<string, bitmap=""> mMemoryCache; 
  2.                                                                
  3. @Override 
  4. protected void onCreate(Bundle savedInstanceState) { 
  5.     ... 
  6.     // Get memory class of this device, exceeding this amount will throw an 
  7.     // OutOfMemory exception. 
  8.     final int memClass = ((ActivityManager) context.getSystemService( 
  9.             Context.ACTIVITY_SERVICE)).getMemoryClass(); 
  10.                                                                
  11.     // Use 1/8th of the available memory for this memory cache. 
  12.     final int cacheSize = 1024 * 1024 * memClass / 8
  13.                                                                
  14.     mMemoryCache = new LruCache<string, bitmap="">(cacheSize) { 
  15.         @Override 
  16.         protected int sizeOf(String key, Bitmap bitmap) { 
  17.             // The cache size will be measured in bytes rather than number of items. 
  18.             return bitmap.getByteCount(); 
  19.         } 
  20.     }; 
  21.     ... 
  22. }                                                               
  23. public void addBitmapToMemoryCache(String key, Bitmap bitmap) { 
  24.     if (getBitmapFromMemCache(key) == null) { 
  25.         mMemoryCache.put(key, bitmap); 
  26.     } 
  27. }                                                               
  28. public Bitmap getBitmapFromMemCache(String key) { 
  29.     return mMemoryCache.get(key); 

注意: 在这个示例中,该程序的1/8内存都用来做缓存用了。在一个normal/hdpi设备中,这至少有4MB(32/8)内存。
在一个分辨率为 800×480的设备中,满屏的GridView全部填充上图片将会使用差不多1.5MB(800*480*4 bytes)
的内存,所以这样差不多在内存中缓存了2.5页的图片。

当在 ImageView 中显示图片的时候,
先检查LruCache 中是否存在。如果存在就使用缓存后的图片,如果不存在就启动后台线程去载入图片并缓存:

  1. public void loadBitmap(int resId, ImageView imageView) { 
  2.     final String imageKey = String.valueOf(resId); 
  3.     final Bitmap bitmap = getBitmapFromMemCache(imageKey); 
  4.     if (bitmap != null) { 
  5.         mImageView.setImageBitmap(bitmap); 
  6.     } else { 
  7.         mImageView.setImageResource(R.drawable.image_placeholder); 
  8.         BitmapWorkerTask task = new BitmapWorkerTask(mImageView); 
  9.         task.execute(resId); 
  10.     } 

BitmapWorkerTask 需要把新的图片添加到缓存中:

  1. class BitmapWorkerTask extends AsyncTask<integer, void,="" bitmap=""> { 
  2.     ... 
  3.     // Decode image in background. 
  4.     @Override 
  5.     protected Bitmap doInBackground(Integer... params) { 
  6.         final Bitmap bitmap = decodeSampledBitmapFromResource( 
  7.                 getResources(), params[0], 100100)); 
  8.         addBitmapToMemoryCache(String.valueOf(params[0]), bitmap); 
  9.         return bitmap; 
  10.     } 
  11.     ... 

下页将为您介绍其它两种方法使用磁盘缓存处理配置改变事件

#p#

使用磁盘缓存

在访问最近使用过的图片中,内存缓存速度很快,但是您无法确定图片是否在缓存中存在。像
GridView 这种控件可能具有很多图片需要显示,很快图片数据就填满了缓存容量。
同时您的程序还可能被其他任务打断,比如打进的电话 — 当您的程序位于后台的时候,系统可能会清楚到这些图片缓存。一旦用户恢复使用您的程序,您还需要重新处理这些图片。

在这种情况下,可以使用磁盘缓存来保存这些已经处理过的图片,当这些图片在内存缓存中不可用的时候,可以从磁盘缓存中加载从而省略了图片处理过程。
当然, 从磁盘载入图片要比从内存读取慢很多,并且应该在非UI线程中载入磁盘图片。

注意: 如果缓存的图片经常被使用的话,可以考虑使用
ContentProvider ,例如在图库程序中就是这样干滴。

在示例代码中有个简单的 DiskLruCache 实现。然后,在Android 4.0中包含了一个更加可靠和推荐使用的DiskLruCache(libcore/luni/src/main/java/libcore/io/DiskLruCache.java)
。您可以很容易的把这个实现移植到4.0之前的版本中使用(来 href="http://www.google.com/search?q=disklrucache">Google一下 看看其他人是否已经这样干了!)。

这里是一个更新版本的 DiskLruCache :

  1. private DiskLruCache mDiskCache; 
  2. private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10// 10MB 
  3. private static final String DISK_CACHE_SUBDIR = "thumbnails"
  4.                                 
  5. @Override 
  6. protected void onCreate(Bundle savedInstanceState) { 
  7.     ... 
  8.     // Initialize memory cache 
  9.     ... 
  10.     File cacheDir = getCacheDir(this, DISK_CACHE_SUBDIR); 
  11.     mDiskCache = DiskLruCache.openCache(this, cacheDir, DISK_CACHE_SIZE); 
  12.     ... 
  13. }                                
  14. class BitmapWorkerTask extends AsyncTask<integer, void,="" bitmap=""> { 
  15.     ... 
  16.     // Decode image in background. 
  17.     @Override 
  18.     protected Bitmap doInBackground(Integer... params) { 
  19.         final String imageKey = String.valueOf(params[0]); 
  20.                                
  21.         // Check disk cache in background thread 
  22.         Bitmap bitmap = getBitmapFromDiskCache(imageKey); 
  23.                                 
  24.         if (bitmap == null) { // Not found in disk cache 
  25.             // Process as normal 
  26.             final Bitmap bitmap = decodeSampledBitmapFromResource( 
  27.                     getResources(), params[0], 100100)); 
  28.         }                               
  29.         // Add final bitmap to caches 
  30.         addBitmapToCache(String.valueOf(imageKey, bitmap); 
  31.                                 
  32.         return bitmap; 
  33.     } 
  34.     ... 
  35. }                                
  36. public void addBitmapToCache(String key, Bitmap bitmap) { 
  37.     // Add to memory cache as before 
  38.     if (getBitmapFromMemCache(key) == null) { 
  39.         mMemoryCache.put(key, bitmap); 
  40.     }                                
  41.     // Also add to disk cache 
  42.     if (!mDiskCache.containsKey(key)) { 
  43.         mDiskCache.put(key, bitmap); 
  44.     } 
  45. }                                
  46. public Bitmap getBitmapFromDiskCache(String key) { 
  47.     return mDiskCache.get(key); 
  48. }                                
  49. // Creates a unique subdirectory of the designated app cache directory. Tries to use external 
  50. // but if not mounted, falls back on internal storage. 
  51. public static File getCacheDir(Context context, String uniqueName) { 
  52.     // Check if media is mounted or storage is built-in, if so, try and use external cache dir 
  53.     // otherwise use internal cache dir 
  54.     final String cachePath = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED 
  55.             || !Environment.isExternalStorageRemovable() ? 
  56.                     context.getExternalCacheDir().getPath() : context.getCacheDir().getPath(); 
  57.     return new File(cachePath + File.separator + uniqueName); 

在UI线程中检测内存缓存,在后台线程中检测磁盘缓存。磁盘操作从来不应该在UI线程中实现。当图片处理完毕后,最终的结果会同时添加到
内存缓存和磁盘缓存中以便将来使用。

处理配置改变事件

运行时的配置变更 — 例如 屏幕方向改变 — 导致Android摧毁正在运行的Activity,然后使用
新的配置从新启动该Activity (详情,参考这里 Handling Runtime Changes)。
您需要注意避免在配置改变的时候导致重新处理所有的图片,从而提高用户体验。

幸运的是,您在 使用内存缓存 部分已经有一个很好的图片缓存了。该缓存可以通过
Fragment (Fragment会通过setRetainInstance(true)函数保存起来)来传递给新的Activity
当Activity重新启动 后,Fragment 被重新附加到Activity中,您可以通过该Fragment来获取缓存对象。

下面是一个在 Fragment中保存缓存的示例:

  1. private LruCache<string, bitmap=""> mMemoryCache;                  
  2. @Override 
  3. protected void onCreate(Bundle savedInstanceState) { 
  4.     ... 
  5.     RetainFragment mRetainFragment =            RetainFragment.findOrCreateRetainFragment(getFragmentManager()); 
  6.     mMemoryCache = RetainFragment.mRetainedCache; 
  7.     if (mMemoryCache == null) { 
  8.         mMemoryCache = new LruCache<string, bitmap="">(cacheSize) { 
  9.             ... // Initialize cache here as usual 
  10.         } 
  11.         mRetainFragment.mRetainedCache = mMemoryCache; 
  12.     } 
  13.     ... 
  14. }                  
  15. class RetainFragment extends Fragment { 
  16.     private static final String TAG = "RetainFragment"
  17.     public LruCache<string, bitmap=""> mRetainedCache; 
  18.                
  19.     public RetainFragment() {}                  
  20.     public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) { 
  21.         RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG); 
  22.         if (fragment == null) { 
  23.             fragment = new RetainFragment(); 
  24.         } 
  25.         return fragment; 
  26.     }                  
  27.     @Override 
  28.     public void onCreate(Bundle savedInstanceState) { 
  29.         super.onCreate(savedInstanceState); 
  30.         <strong>setRetainInstance(true);</strong> 
  31.     } 

此外您可以尝试分别使用和不使用Fragment来旋转设备的屏幕方向来查看具体的图片载入情况。

责任编辑:闫佳明 来源: cnblogs
相关推荐

2017-02-17 11:50:18

AndroidBitmap缓存池

2013-07-29 16:22:21

Android缓存框架

2023-11-16 08:22:14

LruCacheAndroid

2013-05-21 10:42:48

Android游戏开发Bitmap位图旋转

2013-09-16 16:56:09

AndroidBitmap内存优化

2021-03-29 11:51:07

缓存储存数据

2022-07-07 08:02:49

RedisBitMap

2020-06-18 09:16:20

JavaScript缓存API

2020-07-29 09:13:28

JavaScript开发技术

2019-07-02 15:21:39

缓存NET单线程

2017-12-08 08:58:46

微模块机房服务器

2011-06-01 09:03:12

Android 缓存

2021-01-06 17:28:00

MySQL数据库缓存池

2024-03-15 07:17:51

MySQLLRU算法缓存池

2023-04-26 08:39:41

Bitmap元素存储

2018-10-26 15:54:16

JavaClass常量池

2023-12-19 09:07:05

Android开发内存

2019-09-29 10:29:02

缓存模式微服务架构

2020-01-10 15:42:13

SpringBootRedis数据库

2011-06-01 14:01:45

JavaString
点赞
收藏

51CTO技术栈公众号