android高版本之后,垃圾回收机制更倾向于回收软引用和弱引用,SoftReference属于软引用,所以变得不靠谱了。
android2.3以后退出的LruCache概念,专门用来缓存图片。
工作原理:有个队列专门用来放缓存的,就像是消息队列用来放message一样,只不过在LruCache的队列里,经常使用的缓存图片会不断的从队列中拿出来再次放到队尾,而当队列塞满是,队头的缓存就被挤出去了,被挤出去的缓存就变成软引用,GC一发现,立即清理。这就造成了经常使用的缓存不会被清理,不常用的会被清理,更人性化。
LruCache也要自己手动清理缓存,否则也会OOM。
以下是工具类。
1 public class LruCacheUtils { 2 3 private LruCache<String, Bitmap> mMemoryCache; 4 int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); 5 6 public LruCacheUtils() { 7 if (mMemoryCache == null) 8 mMemoryCache = new LruCache<String, Bitmap>(maxMemory / 8) { 9 @Override 10 protected int sizeOf(String key, Bitmap bitmap) { 11 // 重写此方法来衡量每张图片的大小,默认返回图片数量。 12 return bitmap.getByteCount() / 1024; 13 } 14 }; 15 } 16 17 /** 18 * @param key 添加bitmap到key中 19 * @param bitmap 20 */ 21 public synchronized void addBitmapToMemoryCache(String key, Bitmap bitmap) { 22 // 缓存中已有key的图片 23 if (mMemoryCache.get(key) == null) { 24 return; 25 } 26 if (key != null && bitmap != null) 27 mMemoryCache.put(key, bitmap); 28 } 29 30 /** 31 * @param key 32 * @return 获取为key的bitmap 33 */ 34 public synchronized Bitmap getBitmapFromMemCache(String key) { 35 Bitmap bm = mMemoryCache.get(key); 36 if (key != null) { 37 return bm; 38 } 39 return null; 40 } 41 42 /** 43 * @param key 移除为key的bitmap 44 */ 45 public synchronized void removeImageCache(String key) { 46 if (key == null) { 47 return; 48 } 49 if (mMemoryCache == null) { 50 return; 51 } 52 Bitmap bm = mMemoryCache.remove(key); 53 if (bm != null) 54 bm.recycle(); 55 } 56 57 /** 58 * 移除所有缓存 59 */ 60 public void clearCache() { 61 if (mMemoryCache == null) { 62 return; 63 } 64 if (mMemoryCache.size() <= 0) { 65 return; 66 } 67 mMemoryCache.evictAll(); 68 mMemoryCache = null; 69 } 70 71 }