MemoryCache.java 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package com.easemob.easeui.oss;
  2. import android.graphics.Bitmap;
  3. import java.lang.ref.SoftReference;
  4. import java.util.HashMap;
  5. import java.util.LinkedHashMap;
  6. import java.util.Map;
  7. public class MemoryCache {
  8. // ���Ļ�����
  9. private static final int MAX_CACHE_CAPACITY = 30;
  10. private HashMap<String, SoftReference<Bitmap>> mCacheMap =
  11. new LinkedHashMap<String, SoftReference<Bitmap>>() {
  12. private static final long serialVersionUID = 1L;
  13. protected boolean removeEldestEntry(
  14. Entry<String,SoftReference<Bitmap>> eldest){
  15. return size() > MAX_CACHE_CAPACITY;};
  16. };
  17. public Bitmap get(String id){
  18. if(!mCacheMap.containsKey(id)) return null;
  19. SoftReference<Bitmap> ref = mCacheMap.get(id);
  20. return ref.get();
  21. }
  22. public void put(String id, Bitmap bitmap){
  23. mCacheMap.put(id, new SoftReference<Bitmap>(bitmap));
  24. }
  25. public void clear() {
  26. try {
  27. for(Map.Entry<String,SoftReference<Bitmap>>entry
  28. :mCacheMap.entrySet())
  29. { SoftReference<Bitmap> sr = entry.getValue();
  30. if(null != sr) {
  31. Bitmap bmp = sr.get();
  32. if(null != bmp) bmp.recycle();
  33. }
  34. }
  35. mCacheMap.clear();
  36. } catch (Exception e) {
  37. e.printStackTrace();}
  38. }
  39. }