android 用LruCache读取大图片并缓存(转)
<div id="cnblogs_post_body">图片预取缓存策略是内存缓存(硬引用LruCache、软引用SoftReference<Bitmap>)、外部文件缓存(context.getCachedDir()),缓存中取不到的情况下再向服务端请求下载图片。同时缓存三张图片(当前预览的这张,前一张以及后一张)。1.内存缓存
<div class="cnblogs_code">&bull;//需要导入外部jar文件 android-support-v4.jar &bull;import android.support.v4.util.LruCache; &bull;//开辟8M硬缓存空间 &bull;private final int hardCachedSize = 8*1024*1024; &bull;//hard cache &bull;private final LruCache<String, Bitmap> sHardBitmapCache = new LruCache<String, Bitmap>(hardCachedSize){ &bull;@Override &bull;public int sizeOf(String key, Bitmap value){ &bull;return value.getRowBytes() * value.getHeight(); &bull;} &bull;@Override &bull;protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue){ &bull;Log.v("tag", "hard cache is full , push to soft cache"); &bull;//硬引用缓存区满,将一个最不经常使用的oldvalue推入到软引用缓存区 &bull;sSoftBitmapCahe.put(key, new SoftReference<Bitmap>(oldValue)); &bull;} &bull;} &bull;//软引用 &bull;private static final int SOFT_CACHE_CAPACITY = 40; &bull;private final static LinkedHashMap<String, SoftReference<Bitmap>> sSoftBitmapCache = &bull;new LinkedHashMao<String, SoftReference<Bitmap>>(SOFT_CACHE_CAPACITY, 0.75f, true){ &bull;@Override &bull;public SoftReference<Bitmap> put(String key, SoftReference<Bitmap> value){ &bull;return super.input(key, value); &bull;} &bull;@Override &bull;protected boolean removeEldestEntry(LinkedHashMap.Entry<Stirng, SoftReference<Bitmap>> eldest){ &bull;if(size() > SOFT_CACHE_CAPACITY){ &bull;Log.v("tag", "Soft Reference limit , purge one"); &bull;return true; &bull;} &bull;return false; &bull;} &bull;} &bull;//缓存bitmap &bull;public boolean putBitmap(String key, Bitmap bitmap){ &bull;if(bitmap != null){ &bull;synchronized(sHardBitmapCache){ &bull;sHardBitmapCache.put(key, bitmap); &bull;} &bull;return true; &bull;} &bull;return false; &bull;} &bull;//从缓存中获取bitmap &bull;public Bitmap getBitmap(String key){ &bull;synchronized(sHardBitmapCache){ &bull;final Bitmap bitmap = sHardBitmapCache.get(key); &bull;if(bitmap != null) &bull;return bitmap; &bull;} &bull;//硬引用缓存区间中读取失败,从软引用缓存区间读取 &bull;synchronized(sSoftBitmapCache){ &bull;SoftReference<Bitmap> bitmapReference = sSoftBtimapCache.get(key); &bull;if(bitmapReference != null){ &bull;final Bitmap bitmap2 = bitmapReference.get(); &bull;if(bitmap2 != null) &bull;return bitmap2; &bull;else{ &bull;Log.v("tag", "soft reference 已经被回收"); &bull;sSoftBitmapCache.remove(key); &bull;} &bull;} &bull;} &bull;return null; &bull;}
页:
[1]