优化的Bitmap缓存类

package Utils;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import android.graphics.Bitmap;

/**
 * 优化的bitmap缓存,自动管理缓存,可以设置缓存大小,大于缓存的内容将被移入 轻量级缓存。
 * 
 * @author [email protected]
 * 
 */
public class BitmapCache {
 /**
  * 缓存大小
  */
 private static int BUFFER_SIZE = 30;
 private static BitmapCache cache;
 private HashMap<String, SoftReference<Bitmap>> mImageSoftCache;
 private HashMap<String, Bitmap> mImageCache;
 private List<String> mKeySet;

 public static int getBUFFER_SIZE() {
  return BUFFER_SIZE;
 }
 
 /**
  * 设置缓存大小,超过这个大小的的将被移入softCache.默认大小为25
  * @param bUFFER_SIZE
  */
 public static void setBUFFER_SIZE(int bUFFER_SIZE) {
  BUFFER_SIZE = bUFFER_SIZE;
 }
 
 private BitmapCache() {
  mImageSoftCache = new HashMap<String, SoftReference<Bitmap>>();
  mImageCache = new HashMap<String, Bitmap>();
  mKeySet = new LinkedList<String>();
 }

 public static BitmapCache getInstance() {
  if (cache == null) {
   cache = new BitmapCache();
  }
  return cache;

 }

 /***
  * @param key
  *            image name
  * @return
  */
 public Bitmap getBitmap(String key) {
  if (mImageCache.containsKey(key)) {
   return mImageCache.get(key);
  } else if(mImageSoftCache.containsKey(key)){
   if (mKeySet.size() < BUFFER_SIZE) {
    return null;
   } else{
   SoftReference<Bitmap> reference = mImageSoftCache.get(key);
   Bitmap bitmap = reference.get();
   if (bitmap != null)
    return bitmap;
   }
  }
  return null;
 }

 /**
  * 添加到缓存
  * 
  * @param key
  * @param bm
  */
 public void put(String key, Bitmap bm) {
  if (mKeySet.size() <= BUFFER_SIZE) {
   mImageCache.put(key, bm);
   mKeySet.add(key);
  } else {
   mKeySet.add(key);
   final String softKey = mKeySet.remove(0);
   final Bitmap softBitmap = mImageCache.remove(softKey);
   putSoftReference(softKey, softBitmap);
  }
 }

 /***
  * 
  * @param bitmap
  * @param key
  */
 public void putSoftReference(String key, Bitmap bitmap) {
  mImageSoftCache.put(key, new SoftReference<Bitmap>(bitmap));
 }
 
 /**
  * 回收缓存类,便于重用。
  */
 public void recycle(){
  mImageCache.clear();
  mImageSoftCache.clear();
  mKeySet.clear();
 }
}

你可能感兴趣的:(android,性能优化,bitmap缓存)