Lrucache缓存技术

在Android中,有一个叫做LruCache类专门用来做图片缓存处理的。
它有一个特点,当缓存的图片达到了预先设定的值的时候,那么近期使用次数最少的图片就会被回收掉
步骤: (1)要先设置缓存图片的内存大小,我这里设置为手机内存的1/8,手机内存的获取方式:int MAXMEMONRY = (int) (Runtime.getRuntime() .maxMemory() / 1024);
    (2)LruCache里面的键值对分别是URL和对应的图片
    (3)重写了一个叫做sizeOf的方法,返回的是图片数量。

 1     private LruCache<String, Bitmap> mMemoryCache;
 2     private LruCacheUtils() {
 3             if (mMemoryCache == null)
 4                 mMemoryCache = new LruCache<String, Bitmap>(
 5                         MAXMEMONRY / 8) {
 6                     @Override
 7                     protected int sizeOf(String key, Bitmap bitmap) {
 8                         // 重写此方法来衡量每张图片的大小,默认返回图片数量。
 9                         return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
10                     }
11 
12                     @Override
13                     protected void entryRemoved(boolean evicted, String key,
14                             Bitmap oldValue, Bitmap newValue) {
15                         Log.v("tag", "hard cache is full , push to soft cache");
16                       
17                     }
18                 };
19         }

 

     (4)下面的方法分别是清空缓存、添加图片到缓存、从缓存中取得图片、从缓存中移除。
          移除和清除缓存是必须要做的事,因为图片缓存处理不当就会报内存溢出,所以一定要引起注意。

 1     public void clearCache() {
 2             if (mMemoryCache != null) {
 3                 if (mMemoryCache.size() > 0) {
 4                     Log.d("CacheUtils",
 5                             "mMemoryCache.size() " + mMemoryCache.size());
 6                     mMemoryCache.evictAll();
 7                     Log.d("CacheUtils", "mMemoryCache.size()" + mMemoryCache.size());
 8                 }
 9                 mMemoryCache = null;
10             }
11         }
12 
13         public synchronized void addBitmapToMemoryCache(String key, Bitmap bitmap) {
14             if (mMemoryCache.get(key) == null) {
15                 if (key != null && bitmap != null)
16                     mMemoryCache.put(key, bitmap);
17             } else
18                 Log.w(TAG, "the res is aready exits");
19         }
20 
21         public synchronized Bitmap getBitmapFromMemCache(String key) {
22             Bitmap bm = mMemoryCache.get(key);
23             if (key != null) {
24                 return bm;
25             }
26             return null;
27         }
28 
29         /**
30          * 移除缓存
31          *
32          * @param key
33          */
34         public synchronized void removeImageCache(String key) {
35             if (key != null) {
36                 if (mMemoryCache != null) {
37                     Bitmap bm = mMemoryCache.remove(key);
38                     if (bm != null)
39                         bm.recycle();
40                 }
41             }
42         }

 

posted @ 2016-08-17 14:54  点滴之水  阅读(2011)  评论(0编辑  收藏  举报