一个bitmap缓存的工具类

项目中用到了很多图片,所以写了个bitmap缓存的工具类

package cn.com.shine.pdi.hptv.util;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

public class BitmapCache {
	private static LruCache mMemoryCache;
	private static int MAXMEMONRY = (int) (Runtime.getRuntime() .maxMemory() / 1024);
	private static BitmapCache instance;
	
	public static BitmapCache getInstance(){
		if (instance == null) {
			instance = new BitmapCache();
		}
		initCache();
		return instance;
	}
	
	private static void initCache() {
        if (mMemoryCache == null){
            mMemoryCache = new LruCache(
                    MAXMEMONRY / 8) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    // 重写此方法来衡量每张图片的大小,默认返回图片数量。
                    return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
                }

                @Override
                protected void entryRemoved(boolean evicted, String key,
                        Bitmap oldValue, Bitmap newValue) {
                	LogUtil.i("hard cache is full , push to soft cache");
                   
                }
            };
        }
    }
		
		
	public void clearCache() {
        if (mMemoryCache != null) {
            if (mMemoryCache.size() > 0) {
            	LogUtil.i(
                        "mMemoryCache.size() " + mMemoryCache.size());
                mMemoryCache.evictAll();
                LogUtil.i( "mMemoryCache.size()" + mMemoryCache.size());
            }
            mMemoryCache = null;
        }
    }

	public synchronized void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (mMemoryCache.get(key) == null) {
            if (key != null && bitmap != null)
                mMemoryCache.put(key, bitmap);
        } else
            LogUtil.i("the res is aready exits");
    }

	public synchronized Bitmap getBitmapFromMemCache(String key) {
        Bitmap bm = mMemoryCache.get(key);
        if (bm != null) {
            return bm;
        }
        return null;
    }

    /**
     * 移除缓存
     * 
     * @param key
     */
	public synchronized void removeImageCache(String key) {
        if (key != null) {
            if (mMemoryCache != null) {
                Bitmap bm = mMemoryCache.remove(key);
                if (bm != null)
                    bm.recycle();
            }
        }
    }
}

在项目里面就可以使用了,例如:

Bitmap bm = mCache.getBitmapFromMemCache(path);
if (bm == null) {
	bm = ImageUtils.getBitmap(path, width, height);
	mCache.addBitmapToMemoryCache(path, bm);
		}
	bm = mCache.getBitmapFromMemCache(path);
	imageView.setImageBitmap(bm);


你可能感兴趣的:(android)