Android中高效的显示图片之三——缓存图片

    加载一张图片到UI相对比较简单,如果一次要加载一组图片,就会变得麻烦很多。像ListView,GridView,ViewPager等控件,需要显示的图片和将要显示的图片数量可能会很大。

    为了减少内存使用,这类控件都重复利用移出屏幕的子视图,如果你没有持用引用,垃圾回收器也会回收你加载过的图片。这种做法很好,但是如果想要图片加载快速流畅且不想当控件拖回来时重新运算获取加载过的图片,通常会使用内存和磁盘缓存。这节主要介绍当加载多张图片时利用内存缓存和磁盘缓存使加载图片时更快。

一、使用内存缓存

    内存缓存以牺牲有限的应用内存为代价提供快速访问缓存的图片方法。LruCache类(有兼容包可以支持到API Level 4)很适合缓存图片的功能,它在LinkedHashMap中保存着最近使用图片对象的引用,并且在内容超过它指定的容量前删除近期最少使用的对象的引用。

    注意:这前,很流行的图片缓存的方法是使用SoftReference和WeakReference,但是这种方法不提倡。因为从Android2.3(Level 9)开始,内存回收器会对软引用和弱引用进行回收。另外,在Android3.0(Levle 11)之前,图片的数据是存储在系统native内存中的,它的内存释放不可预料,这也是造成程序内存溢出的一个潜在原因。

    为了给LruCache选择一个合适的大小,一些因素需要考虑:

》应用其它的模块对内存大小的要求

》有多少张图片会同时在屏幕上显示,有多少张图片需要提前加载

》屏幕的大小和密度

》图片的尺寸和设置

》图片被访问的频度

》平衡数量和质量,有时候存储大量的低质量的图片会比少量的高质量图片要有用

对于缓存,没有大小或者规则适用于所有应用,它依赖于你分析自己应用的内存使用确定自己的方案。缓存太小可能只会增加额外的内存使用,缓存太大可能会导致内存溢出或者应用其它模块可使用内存太小。

下面是为图片缓存设置LruCache的一个例子:

  1. private LruCache 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(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.   
  24. public void addBitmapToMemoryCache(String key, Bitmap bitmap) {  
  25.     if (getBitmapFromMemCache(key) == null) {  
  26.         mMemoryCache.put(key, bitmap);  
  27.     }  
  28. }  
  29.   
  30. public Bitmap getBitmapFromMemCache(String key) {  
  31.     return mMemoryCache.get(key);  
  32. }  


注意:这个例子中,应用内存的1/8用来做缓存。在普通hdpi设备上这个值通常为4M(32/8)。一个全屏的GridView,尺寸为800x480大小通常为1.5M左右(800*480*4sbytes),所以在内存中可以缓存2.5张图片。

    当一个ImageView加载图片时,先检查LruCache。如果缓存中存在,会用它马上更新ImageView,否则的话,启动一个后台线程来加载图片:

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


BitmapWorkerTask加载图片后,也要把图片缓存到内存中:

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

二、使用磁盘缓存

    内存缓存最加载最近访问过的图片有很大帮助,但你并不能依赖于图片会存在于缓存中。像GridView这样的控件如果数据稍微多一点,就可以轻易的把内存缓存用完。你的应用也有可能被其他任务打断,如电话呼入,应用在后台有可能会被结束,这样缓存的数据也会丢失。当用户回到应用时,所有的图片还需要重新获取一遍。

    磁盘缓存可应用到这种场景中,它可以减少你获取图片的次数,当然,从磁盘获取图片比从内存中获取要慢的多,所以它需要在非UI线程中完成。示例代码中是磁盘缓存的一个实现,在Android4.0源码中( 

libcore/luni/src/main/java/libcore/io/DiskLruCache.java),有更加强大和推荐的一个实现,它的向后兼容使在已发布过的库中很方便使用它。下面是它的例子:

 

  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.   
  15. class BitmapWorkerTask extends AsyncTask {  
  16.     ...  
  17.     // Decode image in background.  
  18.     @Override  
  19.     protected Bitmap doInBackground(Integer... params) {  
  20.         final String imageKey = String.valueOf(params[0]);  
  21.   
  22.         // Check disk cache in background thread  
  23.         Bitmap bitmap = getBitmapFromDiskCache(imageKey);  
  24.   
  25.         if (bitmap == null) { // Not found in disk cache  
  26.             // Process as normal  
  27.             final Bitmap bitmap = decodeSampledBitmapFromResource(  
  28.                     getResources(), params[0], 100, 100));  
  29.         }  
  30.   
  31.         // Add final bitmap to caches  
  32.         addBitmapToCache(String.valueOf(imageKey, bitmap);  
  33.   
  34.         return bitmap;  
  35.     }  
  36.     ...  
  37. }  
  38.   
  39. public void addBitmapToCache(String key, Bitmap bitmap) {  
  40.     // Add to memory cache as before  
  41.     if (getBitmapFromMemCache(key) == null) {  
  42.         mMemoryCache.put(key, bitmap);  
  43.     }  
  44.   
  45.     // Also add to disk cache  
  46.     if (!mDiskCache.containsKey(key)) {  
  47.         mDiskCache.put(key, bitmap);  
  48.     }  
  49. }  
  50.   
  51. public Bitmap getBitmapFromDiskCache(String key) {  
  52.     return mDiskCache.get(key);  
  53. }  
  54.   
  55. // Creates a unique subdirectory of the designated app cache directory. Tries to use external  
  56. // but if not mounted, falls back on internal storage.  
  57. public static File getCacheDir(Context context, String uniqueName) {  
  58.     // Check if media is mounted or storage is built-in, if so, try and use external cache dir  
  59.     // otherwise use internal cache dir  
  60.     final String cachePath = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED  
  61.             || !Environment.isExternalStorageRemovable() ?  
  62.                     context.getExternalCacheDir().getPath() : context.getCacheDir().getPath();  
  63.   
  64.     return new File(cachePath + File.separator + uniqueName);  
  65. }  


在UI线程中检查内存缓存,而在后台线程中检查磁盘缓存。磁盘操作最好永远不要在UI线程中进行。当图片获取完成,把它同时缓存到内存中和磁盘中。

三、处理配置改变

运行时的配置改变,例如屏幕横竖屏切换,会导致系统结束当前正在运行的Activity并用新配置重新启动(可参考:http://developer.android.com/guide/topics/resources/runtime-changes.html)。为了有好的用户体验,你可能不想在这种情况下,重新获取一遍图片。幸好你可以使用上面讲的内存缓存。缓存可以通过使用一个Fragment(调用setRetainInstance(true)被传到新的Activity,当新的Activity被创建后,只需要重新附加Fragment,你就可以得到这个Fragment并访问到存在的缓存,把里面的图片快速的显示出来。下面是一个示例:
 
  1. private LruCache mMemoryCache;  
  2.   
  3. @Override  
  4. protected void onCreate(Bundle savedInstanceState) {  
  5.     ...  
  6.     RetainFragment mRetainFragment =  
  7.             RetainFragment.findOrCreateRetainFragment(getFragmentManager());  
  8.     mMemoryCache = RetainFragment.mRetainedCache;  
  9.     if (mMemoryCache == null) {  
  10.         mMemoryCache = new LruCache(cacheSize) {  
  11.             ... // Initialize cache here as usual  
  12.         }  
  13.         mRetainFragment.mRetainedCache = mMemoryCache;  
  14.     }  
  15.     ...  
  16. }  
  17.   
  18. class RetainFragment extends Fragment {  
  19.     private static final String TAG = "RetainFragment";  
  20.     public LruCache mRetainedCache;  
  21.   
  22.     public RetainFragment() {}  
  23.   
  24.     public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {  
  25.         RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);  
  26.         if (fragment == null) {  
  27.             fragment = new RetainFragment();  
  28.         }  
  29.         return fragment;  
  30.     }  
  31.   
  32.     @Override  
  33.     public void onCreate(Bundle savedInstanceState) {  
  34.         super.onCreate(savedInstanceState);  
  35.         setRetainInstance(true);  
  36.     }  
  37. }  
原文地址:https://www.cnblogs.com/chengzhengfu/p/4579271.html