在Android中,有一個叫做LruCache類專門用來做圖片緩存處理的。
它有一個特點,當緩存的圖片達到了預先設定的值的時候,那么近期使用次數最少的圖片就會被回收掉。
步驟: (1)要先設置緩存圖片的內存大小,我這里設置為手機內存的1/8,手機內存的獲取方式:int MAXMEMONRY = (int) (Runtime.getRuntime() .maxMemory() / 1024);
(2)LruCache里面的鍵值對分別是URL和對應的圖片
(3)重寫了一個叫做sizeOf的方法,返回的是圖片數量。
1 private LruCache<String, Bitmap> mMemoryCache; 2 private LruCacheUtils() { 3 if (mMemoryCache == null) 4 mMemoryCache = new LruCache<String, Bitmap>( 5 MAXMEMONRY / 8) { 6 @Override 7 protected int sizeOf(String key, Bitmap bitmap) { 8 // 重寫此方法來衡量每張圖片的大小,默認返回圖片數量。 9 return bitmap.getRowBytes() * bitmap.getHeight() / 1024; 10 } 11 12 @Override 13 protected void entryRemoved(boolean evicted, String key, 14 Bitmap oldValue, Bitmap newValue) { 15 Log.v("tag", "hard cache is full , push to soft cache"); 16 17 } 18 }; 19 }
(4)下面的方法分別是清空緩存、添加圖片到緩存、從緩存中取得圖片、從緩存中移除。
移除和清除緩存是必須要做的事,因為圖片緩存處理不當就會報內存溢出,所以一定要引起注意。
1 public void clearCache() { 2 if (mMemoryCache != null) { 3 if (mMemoryCache.size() > 0) { 4 Log.d("CacheUtils", 5 "mMemoryCache.size() " + mMemoryCache.size()); 6 mMemoryCache.evictAll(); 7 Log.d("CacheUtils", "mMemoryCache.size()" + mMemoryCache.size()); 8 } 9 mMemoryCache = null; 10 } 11 } 12 13 public synchronized void addBitmapToMemoryCache(String key, Bitmap bitmap) { 14 if (mMemoryCache.get(key) == null) { 15 if (key != null && bitmap != null) 16 mMemoryCache.put(key, bitmap); 17 } else 18 Log.w(TAG, "the res is aready exits"); 19 } 20 21 public synchronized Bitmap getBitmapFromMemCache(String key) { 22 Bitmap bm = mMemoryCache.get(key); 23 if (key != null) { 24 return bm; 25 } 26 return null; 27 } 28 29 /** 30 * 移除緩存 31 * 32 * @param key 33 */ 34 public synchronized void removeImageCache(String key) { 35 if (key != null) { 36 if (mMemoryCache != null) { 37 Bitmap bm = mMemoryCache.remove(key); 38 if (bm != null) 39 bm.recycle(); 40 } 41 } 42 }