xuxiuxi
2017-08-11 5f12988a77d078a5e5155c9a301e45bfd288d7e5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package cn.com.basic.face.util.bitmap;
 
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
 
import java.lang.ref.SoftReference;
 
/**
 * 内存缓存
 * 
 * @author Kevin
 * 
 */
public class MemoryCacheUtils {
 
//     private HashMap<String, SoftReference<Bitmap>> mMemoryCache = new
//     HashMap<String, SoftReference<Bitmap>>();
    private LruCache<String, Bitmap> mMemoryCache;
 
    public MemoryCacheUtils() {
        long maxMemory = Runtime.getRuntime().maxMemory() / 8;// 模拟器默认是16M
        mMemoryCache = new LruCache<String, Bitmap>((int) maxMemory) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                int byteCount = value.getRowBytes() * value.getHeight();// 获取图片占用内存大小
                return byteCount;
            }
        };
    }
 
    /**
     * 从内存读
     * 
     * @param url
     */
    public Bitmap getBitmapFromMemory(String url) {
        // SoftReference<Bitmap> softReference = mMemoryCache.get(url);
        // if (softReference != null) {
        // Bitmap bitmap = softReference.get();
        // return bitmap;
        // }
        return mMemoryCache.get(url);
    }
 
    /**
     * 写内存
     * 
     * @param url
     * @param bitmap
     */
    public void setBitmapToMemory(String url, Bitmap bitmap) {
//         SoftReference<Bitmap> softReference = new
//         SoftReference<Bitmap>(bitmap);
//         mMemoryCache.put(url, softReference);
        mMemoryCache.put(url, bitmap);
    }
}