android中图片内存缓存的工具类的实现
2013-12-23 21:28
441 查看
android中实现图片缓存的工具类的实现:
package com.demo.loading; import java.lang.ref.SoftReference; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.concurrent.ConcurrentHashMap; import android.graphics.Bitmap; /**** * 内存中的缓存 ****/ public class ImageMemoryCache { private static final int HARD_CACHE_CAPACITY = 30; private HashMap<String, Bitmap> mHardBitmapCache; private final static ConcurrentHashMap<String, SoftReference<Bitmap>> mSoftBitmapCache = new ConcurrentHashMap<String, SoftReference<Bitmap>>( HARD_CACHE_CAPACITY / 2); public ImageMemoryCache() { mHardBitmapCache = new LinkedHashMap<String, Bitmap>( HARD_CACHE_CAPACITY / 2, 0.75f, true) { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry( LinkedHashMap.Entry<String, Bitmap> eldest) { if (size() > HARD_CACHE_CAPACITY) { // Entries push-out of hard reference cache are transferred // to soft reference cache mSoftBitmapCache.put(eldest.getKey(), new SoftReference<Bitmap>(eldest.getValue())); return true; } else return false; } }; } /** * 从缓存中获取图片 */ public Bitmap getBitmapFromCache(String url) { // 先从mHardBitmapCache缓存中获取 synchronized (mHardBitmapCache) { final Bitmap bitmap = mHardBitmapCache.get(url); if (bitmap != null) { // 如果找到的话,把元素移到linkedhashmap的最前面,从而保证在LRU算法中是最后被删除 mHardBitmapCache.remove(url); mHardBitmapCache.put(url, bitmap); return bitmap; } } // 如果mHardBitmapCache中找不到,到mSoftBitmapCache中找 SoftReference<Bitmap> bitmapReference = mSoftBitmapCache.get(url); if (bitmapReference != null) { final Bitmap bitmap = bitmapReference.get(); if (bitmap != null) { // 将图片移回硬缓存 mHardBitmapCache.put(url, bitmap); mSoftBitmapCache.remove(url); return bitmap; } else { mSoftBitmapCache.remove(url); } } return null; } /*** 添加图片到缓存 ***/ public void addBitmapToCache(String url, Bitmap bitmap) { if (bitmap != null) { synchronized (mHardBitmapCache) { mHardBitmapCache.put(url, bitmap); } } } }
相关文章推荐
- Android 下Qt 多层窗口关闭时程序退出的问题 解决
- android使用ViewGroup实现滑动菜单
- 【Android】中兴ZTE sdcard路径的问题
- Android基础学习之Activity生命周期
- Android Studio 0.4 + PhoneGap 3.3 开发环境的搭建
- [Android]内存泄露排查实战手记
- Android 自动化测试用例规范
- 开发者必知:提升Android应用开发性能的十大要点
- 有效控制Android应用程序的耗电量
- android activity详解四:保存activity的状态的更多事项
- android activity详解三:保存activity的状态
- android实现session保持
- android activity详解二:Activity的生命周期
- Android开发指南(33) —— Multimedia and Camera - Camera
- android activity详解一:概述
- android:descendantFocusability用法
- android sqllite存储
- Android单元测试
- 两个android模拟器实现打电话发短信的模拟状态
- 菜鸟Android学习之路22——网格视图