使用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來旋轉設備的屏幕方向來查看具體的圖片載入狀況。
相關文章
相關標籤/搜索