您的位置:首页 > 理论基础 > 计算机网络

LruCache和DiskLruCache优化网络异步加载图片

2015-11-12 18:14 513 查看
1. 使用DiskLruCache磁盘缓存网络下载的图片

2. 使用LruCache加载图片到内存

处理逻辑:

1. 优先加载LruCache中的图片,第一步检查LruCahce

2. 第二步检查磁盘缓存DiskLruCache,存在则加入LruCahce,没有则执行第三步

3. 第三步,都没有则去网络下载,下载完成后加入磁盘缓存,更新界面

LruCache用法

private LruCache<Integer, Bitmap> lruCache;

public void addBitmapToMemoryCache(Integer key, Bitmap bitmap)
{
if (getBitmapFromMemCache(key) == null)
{
lruCache.put(key, bitmap);
}
}

public Bitmap getBitmapFromMemCache(Integer key)
{
return lruCache.get(key);
}


DiskLruCache用法

public class DiskCacheManager
{
private Context			context;

/** 磁盘缓存 */
private DiskLruCache		diskCache;

/** cache大小,默认10M */
private final int		MAX_CACHE_SIZE	= 10 * 1024 * 1024;

private static DiskCacheManager diskCacheManager;

private DiskCacheManager()
{
context = ISApplication.getInstance();
initDiskCache();
}

public static DiskCacheManager getInstance()
{
if (diskCacheManager == null)
{
diskCacheManager = new DiskCacheManager();
}
return diskCacheManager;
}

private boolean initDiskCache()
{
try
{
File cacheDir = Enviroment.getInstance().getDiskCacheDir(context, "bitmap");
if (!cacheDir.exists())
{
cacheDir.mkdirs();
}
diskCache = DiskLruCache.open(cacheDir, SystemUtils.getVersionCode(context), 1, MAX_CACHE_SIZE);
return true;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}

/**
*	创建编辑器
* DiskLruCache.Editor editor = diskCache.edit(key);
*  打开输出流
* OutputStream output = editor.newOutputStream(0);
* output.write();
* output.flush();
*  提交
* editor.commit();
* @return
*/
public DiskLruCache getDiskCache()
{
if (diskCache == null || diskCache.isClosed())
{
initDiskCache();
}
return diskCache;
}

public boolean isClosed()
{
if (diskCache != null)
{
return diskCache.isClosed();
}
return true;
}

public void closeCache()
{
if (diskCache == null)
{
return;
}

if (diskCache.isClosed())
{
return;
}

try
{
diskCache.close();
diskCache = null;
}
catch (IOException e)
{
e.printStackTrace();
}
}
}


<pre name="code" class="java">	private DiskLruCache	diskCache;
diskCache = DiskCacheManager.getInstance().getDiskCache();
try
{
String cacheKey = String.valueOf(uid);
Snapshot snapShot = diskCache.get(cacheKey);
if (snapShot != null)
{
// 存在缓存,读取缓存
InputStream input = snapShot.getInputStream(0);
Bitmap bmp = BitmapFactory.decodeStream(input);
if (bmp != null)
{
scaleBitmap(bmp);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}

// 编辑
DiskLruCache.Editor editor = diskCache.edit(cacheKey);
OutputStream output = null;
try
{
if (editor != null)
{
output = editor.newOutputStream(0);
byte[] data = BitmapUtils.bitmap2Bytes(bitmap);
output.write(data);
output.flush();
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (output != null)
{
output.close();
editor.commit();
}
}
catch (Exception e2)
{
e2.printStackTrace();
}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: