其实,在真正的项目实战当中如果仅仅是使用硬盘缓存的话,程序是有明显短板的。而如果只使用内存缓存的话,程序当然也会有很大的缺陷。因此,一个优秀的程序必然会将内存缓存和硬盘缓存结合到一起使用,那么本篇文章我们就来看一看,如何才能将lrucache和disklrucache完美结合到一起。
那我们开始动手吧,新建一个android项目,起名叫photowalldemo,这里我使用的是android 4.0的api。然后新建一个libcore.io包,并将disklrucache.java文件拷贝到这个包下,这样就把准备工作完成了。
接下来首先需要考虑的仍然是图片源的问题,简单起见,我仍然是吧所有图片都上传到了我的csdn相册当中,然后新建一个images类,将所有相册中图片的网址都配置进去,代码如下所示:
public class images {
public final static string[] imagethumburls = new string[] {
"http://img.my.csdn.net/uploads/201407/26/1406383299_1976.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383291_6518.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383291_8239.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383290_9329.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383290_1042.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383275_3977.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383265_8550.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383264_3954.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383264_4787.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383264_8243.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383248_3693.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383243_5120.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383242_3127.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383242_9576.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383242_1721.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383219_5806.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383214_7794.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383213_4418.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383213_3557.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383210_8779.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383172_4577.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383166_3407.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383166_2224.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383166_7301.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383165_7197.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383150_8410.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383131_3736.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383130_5094.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383130_7393.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383129_8813.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383100_3554.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383093_7894.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383092_2432.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383092_3071.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383091_3119.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383059_6589.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383059_8814.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383059_2237.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383058_4330.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406383038_3602.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382942_3079.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382942_8125.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382942_4881.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382941_4559.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382941_3845.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382924_8955.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382923_2141.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382923_8437.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382922_6166.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382922_4843.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382905_5804.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382904_3362.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382904_2312.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382904_4960.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382900_2418.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382881_4490.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382881_5935.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382880_3865.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382880_4662.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382879_2553.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382862_5375.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382862_1748.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382861_7618.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382861_8606.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382861_8949.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382841_9821.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382840_6603.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382840_2405.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382840_6354.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382839_5779.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382810_7578.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382810_2436.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382809_3883.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382809_6269.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382808_4179.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382790_8326.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382789_7174.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382789_5170.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382789_4118.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382788_9532.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382767_3184.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382767_4772.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382766_4924.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382766_5762.jpg",
"http://img.my.csdn.net/uploads/201407/26/1406382765_7341.jpg"
};
}
设置好了图片源之后,我们需要一个gridview来展示照片墙上的每一张图片。打开或修改activity_main.xml中的代码,如下所示:
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<gridview
android:id="@+id/photo_wall"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnwidth="@dimen/image_thumbnail_size"
android:gravity="center"
android:horizontalspacing="@dimen/image_thumbnail_spacing"
android:numcolumns="auto_fit"
android:stretchmode="columnwidth"
android:verticalspacing="@dimen/image_thumbnail_spacing" >
</gridview>
</linearlayout>
很简单,只是在linearlayout中写了一个gridview而已。接着我们要定义gridview中每一个子view的布局,新建一个photo_layout.xml布局,加入如下代码:
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<imageview
android:id="@+id/photo"
android:layout_centerinparent="true"
android:scaletype="fitxy"
/>
</relativelayout>
仍然很简单,photo_layout.xml布局中只有一个imageview控件,就是用它来显示图片的。这样我们就把所有的布局文件都写好了。
接下来新建photowalladapter做为gridview的适配器,代码如下所示:
public class photowalladapter extends arrayadapter<string> {
/**
* 记录所有正在下载或等待下载的任务。
*/
private set<bitmapworkertask> taskcollection;
* 图片缓存技术的核心类,用于缓存所有下载好的图片,在程序内存达到设定值时会将最少最近使用的图片移除掉。
private lrucache<string, bitmap> mmemorycache;
* 图片硬盘缓存核心类。
private disklrucache mdisklrucache;
* gridview的实例
private gridview mphotowall;
* 记录每个子项的高度。
private int mitemheight = 0;
public photowalladapter(context context, int textviewresourceid, string[] objects,
gridview photowall) {
super(context, textviewresourceid, objects);
mphotowall = photowall;
taskcollection = new hashset<bitmapworkertask>();
// 获取应用程序最大可用内存
int maxmemory = (int) runtime.getruntime().maxmemory();
int cachesize = maxmemory / 8;
// 设置图片缓存大小为程序最大可用内存的1/8
mmemorycache = new lrucache<string, bitmap>(cachesize) {
@override
protected int sizeof(string key, bitmap bitmap) {
return bitmap.getbytecount();
}
};
try {
// 获取图片缓存路径
file cachedir = getdiskcachedir(context, "thumb");
if (!cachedir.exists()) {
cachedir.mkdirs();
// 创建disklrucache实例,初始化缓存数据
mdisklrucache = disklrucache
.open(cachedir, getappversion(context), 1, 10 * 1024 * 1024);
} catch (ioexception e) {
e.printstacktrace();
}
}
@override
public view getview(int position, view convertview, viewgroup parent) {
final string url = getitem(position);
view view;
if (convertview == null) {
view = layoutinflater.from(getcontext()).inflate(r.layout.photo_layout, null);
} else {
view = convertview;
final imageview imageview = (imageview) view.findviewbyid(r.id.photo);
if (imageview.getlayoutparams().height != mitemheight) {
imageview.getlayoutparams().height = mitemheight;
// 给imageview设置一个tag,保证异步加载图片时不会乱序
imageview.settag(url);
imageview.setimageresource(r.drawable.empty_photo);
loadbitmaps(imageview, url);
return view;
* 将一张图片存储到lrucache中。
*
* @param key
* lrucache的键,这里传入图片的url地址。
* @param bitmap
* lrucache的键,这里传入从网络上下载的bitmap对象。
public void addbitmaptomemorycache(string key, bitmap bitmap) {
if (getbitmapfrommemorycache(key) == null) {
mmemorycache.put(key, bitmap);
* 从lrucache中获取一张图片,如果不存在就返回null。
* @return 对应传入键的bitmap对象,或者null。
public bitmap getbitmapfrommemorycache(string key) {
return mmemorycache.get(key);
* 加载bitmap对象。此方法会在lrucache中检查所有屏幕中可见的imageview的bitmap对象,
* 如果发现任何一个imageview的bitmap对象不在缓存中,就会开启异步线程去下载图片。
public void loadbitmaps(imageview imageview, string imageurl) {
bitmap bitmap = getbitmapfrommemorycache(imageurl);
if (bitmap == null) {
bitmapworkertask task = new bitmapworkertask();
taskcollection.add(task);
task.execute(imageurl);
} else {
if (imageview != null && bitmap != null) {
imageview.setimagebitmap(bitmap);
}
} catch (exception e) {
* 取消所有正在下载或等待下载的任务。
public void cancelalltasks() {
if (taskcollection != null) {
for (bitmapworkertask task : taskcollection) {
task.cancel(false);
* 根据传入的uniquename获取硬盘缓存的路径地址。
public file getdiskcachedir(context context, string uniquename) {
string cachepath;
if (environment.media_mounted.equals(environment.getexternalstoragestate())
|| !environment.isexternalstorageremovable()) {
cachepath = context.getexternalcachedir().getpath();
cachepath = context.getcachedir().getpath();
return new file(cachepath + file.separator + uniquename);
* 获取当前应用程序的版本号。
public int getappversion(context context) {
packageinfo info = context.getpackagemanager().getpackageinfo(context.getpackagename(),
0);
return info.versioncode;
} catch (namenotfoundexception e) {
return 1;
* 设置item子项的高度。
public void setitemheight(int height) {
if (height == mitemheight) {
return;
mitemheight = height;
notifydatasetchanged();
* 使用md5算法对传入的key进行加密并返回。
public string hashkeyfordisk(string key) {
string cachekey;
final messagedigest mdigest = messagedigest.getinstance("md5");
mdigest.update(key.getbytes());
cachekey = bytestohexstring(mdigest.digest());
} catch (nosuchalgorithmexception e) {
cachekey = string.valueof(key.hashcode());
return cachekey;
* 将缓存记录同步到journal文件中。
public void fluchcache() {
if (mdisklrucache != null) {
try {
mdisklrucache.flush();
} catch (ioexception e) {
e.printstacktrace();
private string bytestohexstring(byte[] bytes) {
stringbuilder sb = new stringbuilder();
for (int i = 0; i < bytes.length; i++) {
string hex = integer.tohexstring(0xff & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
sb.append(hex);
return sb.tostring();
* 异步下载图片的任务。
* @author guolin
class bitmapworkertask extends asynctask<string, void, bitmap> {
/**
* 图片的url地址
*/
private string imageurl;
@override
protected bitmap doinbackground(string... params) {
imageurl = params[0];
filedescriptor filedescriptor = null;
fileinputstream fileinputstream = null;
snapshot snapshot = null;
// 生成图片url对应的key
final string key = hashkeyfordisk(imageurl);
// 查找key对应的缓存
snapshot = mdisklrucache.get(key);
if (snapshot == null) {
// 如果没有找到对应的缓存,则准备从网络上请求数据,并写入缓存
disklrucache.editor editor = mdisklrucache.edit(key);
if (editor != null) {
outputstream outputstream = editor.newoutputstream(0);
if (downloadurltostream(imageurl, outputstream)) {
editor.commit();
} else {
editor.abort();
}
}
// 缓存被写入后,再次查找key对应的缓存
snapshot = mdisklrucache.get(key);
if (snapshot != null) {
fileinputstream = (fileinputstream) snapshot.getinputstream(0);
filedescriptor = fileinputstream.getfd();
// 将缓存数据解析成bitmap对象
bitmap bitmap = null;
if (filedescriptor != null) {
bitmap = bitmapfactory.decodefiledescriptor(filedescriptor);
if (bitmap != null) {
// 将bitmap对象添加到内存缓存当中
addbitmaptomemorycache(params[0], bitmap);
return bitmap;
} finally {
if (filedescriptor == null && fileinputstream != null) {
try {
fileinputstream.close();
} catch (ioexception e) {
return null;
protected void onpostexecute(bitmap bitmap) {
super.onpostexecute(bitmap);
// 根据tag找到相应的imageview控件,将下载好的图片显示出来。
imageview imageview = (imageview) mphotowall.findviewwithtag(imageurl);
if (imageview != null && bitmap != null) {
imageview.setimagebitmap(bitmap);
taskcollection.remove(this);
* 建立http请求,并获取bitmap对象。
*
* @param imageurl
* 图片的url地址
* @return 解析后的bitmap对象
private boolean downloadurltostream(string urlstring, outputstream outputstream) {
httpurlconnection urlconnection = null;
bufferedoutputstream out = null;
bufferedinputstream in = null;
final url url = new url(urlstring);
urlconnection = (httpurlconnection) url.openconnection();
in = new bufferedinputstream(urlconnection.getinputstream(), 8 * 1024);
out = new bufferedoutputstream(outputstream, 8 * 1024);
int b;
while ((b = in.read()) != -1) {
out.write(b);
return true;
} catch (final ioexception e) {
if (urlconnection != null) {
urlconnection.disconnect();
try {
if (out != null) {
out.close();
if (in != null) {
in.close();
} catch (final ioexception e) {
e.printstacktrace();
return false;
代码有点长,我们一点点进行分析。首先在photowalladapter的构造函数中,我们初始化了lrucache类,并设置了内存缓存容量为程序最大可用内存的1/8,紧接着调用了disklrucache的open()方法来创建实例,并设置了硬盘缓存容量为10m,这样我们就把lrucache和disklrucache的初始化工作完成了。
接着在getview()方法中,我们为每个imageview设置了一个唯一的tag,这个tag的作用是为了后面能够准确地找回这个imageview,不然异步加载图片会出现乱序的情况。然后在getview()方法的最后调用了loadbitmaps()方法,加载图片的具体逻辑也就是在这里执行的了。
进入到loadbitmaps()方法中可以看到,实现是调用了getbitmapfrommemorycache()方法来从内存中获取缓存,如果获取到了则直接调用imageview的setimagebitmap()方法将图片显示到界面上。如果内存中没有获取到,则开启一个bitmapworkertask任务来去异步加载图片。
那么在bitmapworkertask的doinbackground()方法中,我们就灵活运用了上篇文章中学习的disklrucache的各种用法。首先根据图片的url生成对应的md5 key,然后调用disklrucache的get()方法来获取硬盘缓存,如果没有获取到的话则从网络上请求图片并写入硬盘缓存,接着将bitmap对象解析出来并添加到内存缓存当中,最后将这个bitmap对象显示到界面上,这样一个完整的流程就执行完了。
那么我们再来分析一下上述流程,每次加载图片的时候都优先去内存缓存当中读取,当读取不到的时候则回去硬盘缓存中读取,而如果硬盘缓存仍然读取不到的话,就从网络上请求原始数据。不管是从硬盘缓存还是从网络获取,读取到了数据之后都应该添加到内存缓存当中,这样的话我们下次再去读取图片的时候就能迅速从内存当中读取到,而如果该图片从内存中被移除了的话,那就重复再执行一遍上述流程就可以了。
这样我们就把lrucache和disklrucache完美结合到一起了。接下来还需要编写mainactivity的代码,非常简单,如下所示:
public class mainactivity extends activity {
* 用于展示照片墙的gridview
* gridview的适配器
private photowalladapter madapter;
private int mimagethumbsize;
private int mimagethumbspacing;
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
mimagethumbsize = getresources().getdimensionpixelsize(
r.dimen.image_thumbnail_size);
mimagethumbspacing = getresources().getdimensionpixelsize(
r.dimen.image_thumbnail_spacing);
mphotowall = (gridview) findviewbyid(r.id.photo_wall);
madapter = new photowalladapter(this, 0, images.imagethumburls,
mphotowall);
mphotowall.setadapter(madapter);
mphotowall.getviewtreeobserver().addongloballayoutlistener(
new viewtreeobserver.ongloballayoutlistener() {
@override
public void ongloballayout() {
final int numcolumns = (int) math.floor(mphotowall
.getwidth()
/ (mimagethumbsize + mimagethumbspacing));
if (numcolumns > 0) {
int columnwidth = (mphotowall.getwidth() / numcolumns)
- mimagethumbspacing;
madapter.setitemheight(columnwidth);
mphotowall.getviewtreeobserver()
.removeglobalonlayoutlistener(this);
});
protected void onpause() {
super.onpause();
madapter.fluchcache();
protected void ondestroy() {
super.ondestroy();
// 退出程序时结束所有的下载任务
madapter.cancelalltasks();
上述代码中,我们通过getviewtreeobserver()的方式监听view的布局事件,当布局完成以后,我们重新修改一下gridview中子view的高度,以保证子view的宽度和高度可以保持一致。
到这里还没有结束,最后还需要配置一下androidmanifest.xml文件,并加入相应的权限,如下所示:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.photoswalldemo"
android:versioncode="1"
android:versionname="1.0" >
<uses-sdk
android:minsdkversion="14"
android:targetsdkversion="17" />
<uses-permission android:name="android.permission.internet" />
<uses-permission android:name="android.permission.write_external_storage" />
<application
android:allowbackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/apptheme" >
<activity
android:name="com.example.photoswalldemo.mainactivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.main" />
<category android:name="android.intent.category.launcher" />
</intent-filter>
</activity>
</application>
</manifest>
好了,全部代码都在这儿了,让我们来运行一下吧,效果如下图所示:
第一次从网络上请求图片的时候有点慢,但之后加载图片就会非常快了,滑动起来也很流畅。
那么我们最后再检查一下这些图片是不是已经正确缓存在指定地址了,进入 /sdcard/android/data/<application package>/cache/thumb 这个路径,如下图所示:
可以看到,每张图片的缓存以及journal文件都在这里了,说明我们的硬盘缓存已经成功了。
好了,今天的讲解就到这里,有疑问的朋友可以在下面留言。
原文地址http://blog.csdn.net/guolin_blog/article/details/34093441
<a target="_blank" href="http://download.csdn.net/detail/sinyu890807/7754669">源码下载,请点击这里</a>