使用LRU算法缓存图片

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

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

这节内容介绍如何使用缓存来提升UI的载入输入和滑动的流畅性。 android

使用内存缓存

内存缓存提升了访问图片的速度,可是要占用很多内存。 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)中,而且达到预约条件后也不会释放这些对象,从而可能致使
程序超过内存限制并崩溃。 app

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

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

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

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

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

  • 图片访问的频率如何?一些图片的访问频率要比其余图片高不少?若是是这样的话,您可能须要把这些常常访问的图片放到内存中。

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

这里没有万能配方能够适合全部的程序,您须要分析您的使用状况并在指定本身的缓存策略。使用过小的缓存并不能起到应有的效果,而使用太大的缓存会消耗更多
的内存从而有可能致使 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); 

private LruCache<string, bitmap=""> mMemoryCache;
                                                              
@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    // Get memory class of this device, exceeding this amount will throw an
    // OutOfMemory exception.
    final int memClass = ((ActivityManager) context.getSystemService(
            Context.ACTIVITY_SERVICE)).getMemoryClass();
                                                              
    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = 1024 * 1024 * memClass / 8;
                                                              
    mMemoryCache = new LruCache<string, bitmap="">(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size will be measured in bytes rather than number of items.
            return bitmap.getByteCount();
        }
    };
    ...
}
                                                              
public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
    if (getBitmapFromMemCache(key) == null) {
        mMemoryCache.put(key, bitmap);
    }
}
                                                              
public Bitmap getBitmapFromMemCache(String key) {
    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.                                                       
  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.     } 

public void loadBitmap(int resId, ImageView imageView) {
    final String imageKey = String.valueOf(resId);
                                                     
    final Bitmap bitmap = getBitmapFromMemCache(imageKey);
    if (bitmap != null) {
        mImageView.setImageBitmap(bitmap);
    } else {
        mImageView.setImageResource(R.drawable.image_placeholder);
        BitmapWorkerTask task = new BitmapWorkerTask(mImageView);
        task.execute(resId);
    }
}

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], 100, 100)); 
  8.         addBitmapToMemoryCache(String.valueOf(params[0]), bitmap); 
  9.         return bitmap; 
  10.     } 
  11.     ... 

class BitmapWorkerTask extends AsyncTask<integer, void,="" bitmap=""> {
    ...
    // Decode image in background.
    @Override
    protected Bitmap doInBackground(Integer... params) {
        final Bitmap bitmap = decodeSampledBitmapFromResource(
                getResources(), params[0], 100, 100));
        addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);
        return bitmap;
    }
    ...
}


使用磁盘缓存

在访问最近使用过的图片中,内存缓存速度很快,可是您没法肯定图片是否在缓存中存在。像
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], 100, 100)); 
  28.         } 
  29.                                 
  30.         // Add final bitmap to caches 
  31.         addBitmapToCache(String.valueOf(imageKey, bitmap); 
  32.                                 
  33.         return bitmap; 
  34.     } 
  35.     ... 
  36.                                 
  37. public void addBitmapToCache(String key, Bitmap bitmap) { 
  38.     // Add to memory cache as before 
  39.     if (getBitmapFromMemCache(key) == null) { 
  40.         mMemoryCache.put(key, bitmap); 
  41.     } 
  42.                                 
  43.     // Also add to disk cache 
  44.     if (!mDiskCache.containsKey(key)) { 
  45.         mDiskCache.put(key, bitmap); 
  46.     } 
  47.                                 
  48. public Bitmap getBitmapFromDiskCache(String key) { 
  49.     return mDiskCache.get(key); 
  50.                                 
  51. // Creates a unique subdirectory of the designated app cache directory. Tries to use external 
  52. // but if not mounted, falls back on internal storage. 
  53. public static File getCacheDir(Context context, String uniqueName) { 
  54.     // Check if media is mounted or storage is built-in, if so, try and use external cache dir 
  55.     // otherwise use internal cache dir 
  56.     final String cachePath = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED 
  57.             || !Environment.isExternalStorageRemovable() ? 
  58.                     context.getExternalCacheDir().getPath() : context.getCacheDir().getPath(); 
  59.                                 
  60.     return new File(cachePath + File.separator + uniqueName); 

private DiskLruCache mDiskCache;
private static final int DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
private static final String DISK_CACHE_SUBDIR = "thumbnails";
                               
@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    // Initialize memory cache
    ...
    File cacheDir = getCacheDir(this, DISK_CACHE_SUBDIR);
    mDiskCache = DiskLruCache.openCache(this, cacheDir, DISK_CACHE_SIZE);
    ...
}
                               
class BitmapWorkerTask extends AsyncTask<integer, void,="" bitmap=""> {
    ...
    // Decode image in background.
    @Override
    protected Bitmap doInBackground(Integer... params) {
        final String imageKey = String.valueOf(params[0]);
                               
        // Check disk cache in background thread
        Bitmap bitmap = getBitmapFromDiskCache(imageKey);
                               
        if (bitmap == null) { // Not found in disk cache
            // Process as normal
            final Bitmap bitmap = decodeSampledBitmapFromResource(
                    getResources(), params[0], 100, 100));
        }
                               
        // Add final bitmap to caches
        addBitmapToCache(String.valueOf(imageKey, bitmap);
                               
        return bitmap;
    }
    ...
}
                               
public void addBitmapToCache(String key, Bitmap bitmap) {
    // Add to memory cache as before
    if (getBitmapFromMemCache(key) == null) {
        mMemoryCache.put(key, bitmap);
    }
                               
    // Also add to disk cache
    if (!mDiskCache.containsKey(key)) {
        mDiskCache.put(key, bitmap);
    }
}
                               
public Bitmap getBitmapFromDiskCache(String key) {
    return mDiskCache.get(key);
}
                               
// Creates a unique subdirectory of the designated app cache directory. Tries to use external
// but if not mounted, falls back on internal storage.
public static File getCacheDir(Context context, String uniqueName) {
    // Check if media is mounted or storage is built-in, if so, try and use external cache dir
    // otherwise use internal cache dir
    final String cachePath = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
            || !Environment.isExternalStorageRemovable() ?
                    context.getExternalCacheDir().getPath() : context.getCacheDir().getPath();
                               
    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.                   
  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<string, bitmap="">(cacheSize) { 
  11.             ... // Initialize cache here as usual 
  12.         } 
  13.         mRetainFragment.mRetainedCache = mMemoryCache; 
  14.     } 
  15.     ... 
  16.                   
  17. class RetainFragment extends Fragment { 
  18.     private static final String TAG = "RetainFragment"
  19.     public LruCache<string, bitmap=""> mRetainedCache; 
  20.                   
  21.     public RetainFragment() {} 
  22.                   
  23.     public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) { 
  24.         RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG); 
  25.         if (fragment == null) { 
  26.             fragment = new RetainFragment(); 
  27.         } 
  28.         return fragment; 
  29.     } 
  30.                   
  31.     @Override 
  32.     public void onCreate(Bundle savedInstanceState) { 
  33.         super.onCreate(savedInstanceState); 
  34.         <strong>setRetainInstance(true);</strong> 
  35.     } 

private LruCache<string, bitmap=""> mMemoryCache;
                 
@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    RetainFragment mRetainFragment =
            RetainFragment.findOrCreateRetainFragment(getFragmentManager());
    mMemoryCache = RetainFragment.mRetainedCache;
    if (mMemoryCache == null) {
        mMemoryCache = new LruCache<string, bitmap="">(cacheSize) {
            ... // Initialize cache here as usual
        }
        mRetainFragment.mRetainedCache = mMemoryCache;
    }
    ...
}
                 
class RetainFragment extends Fragment {
    private static final String TAG = "RetainFragment";
    public LruCache<string, bitmap=""> mRetainedCache;
                 
    public RetainFragment() {}
                 
    public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
        RetainFragment fragment = (RetainFragment) fm.findFragmentByTag(TAG);
        if (fragment == null) {
            fragment = new RetainFragment();
        }
        return fragment;
    }
                 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        <strong>setRetainInstance(true);</strong>
    }
}


您能够尝试分别使用和不使用Fragment来旋转设备的屏幕方向来查看具体的图片载入状况。
相关文章
相关标签/搜索