DiskLrucCache使用的Demo,这个demo是从网络获取一张图片,保存到本地缓存中(sdcard和内存),当下载成功后,再打开不会重新向网络请求图片,而是世界使用本地资源。
要使用DiskLrucCache需要先下载此类. 下载地址点这里
主类:
/**
* DiskLrucCache使用Demo
*
* @author pangzf
* @date 2014年8月12日 下午2:13:26
*/
public class DemoActivity extends Activity {
private DiskLruCache mDiskLrucache;
private ImageView mIvShow;
private String mBitMapUrl;
private String mKey;
private ProgressDialog mPd;
private Handler mHandler = new Handler() {
@Override
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
// 10.下载图片之后展示
boolean isSuccess = (boolean) msg.obj;
if (isSuccess) {
Snapshot snapshot;
try {
snapshot = mDiskLrucache.get(mKey);
InputStream is = snapshot.getInputStream(0);
mIvShow.setImageBitmap(BitmapFactory.decodeStream(is));
} catch (IOException e) {
e.printStackTrace();
}
}
if (mPd != null && mPd.isShowing()) {
mPd.dismiss();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
mIvShow = (ImageView) findViewById(R.id.iv_show);
mPd = new ProgressDialog(DemoActivity.this);
try {
// 1.存放缓存的目录
File directory = DiskLrucacheUtils.getDiskCache(DemoActivity.this,
"bitmap");
// 2.版本号
int appVersion = DiskLrucacheUtils.getAppVersion(DemoActivity.this);
int valueCount = 1;
// 3.缓存的最大值,这里设置10m
long maxSize = 10 * 1024 * 1024;
// 4.打开disklrucache
mDiskLrucache = DiskLruCache.open(directory, appVersion,
valueCount, maxSize);
mBitMapUrl = "https://raw.githubusercontent.com/pangzaifei/LineChartView/master/LineChartView/effice_picture/a.jpg";
if (mDiskLrucache != null) {
// 5.如果在缓存中存在就用缓存中的bitmap,如果不存在上网上下载
mKey = DiskLrucacheUtils.getKey(mBitMapUrl);
Snapshot snapshot = mDiskLrucache.get(mKey);
if (snapshot != null) {
InputStream is = snapshot.getInputStream(0);
Bitmap bitmap = BitmapFactory.decodeStream(is);
if (bitmap != null) {
mIvShow.setImageBitmap(bitmap);
}
} else {
mPd.show();
new Thread() {
public void run() {
// 6.下载图片
mPd.setMessage("正在加载数据....");
userDiskLrucache();
};
}.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void userDiskLrucache() {
try {
String bitMapUrl = "https://raw.githubusercontent.com/pangzaifei/LineChartView/master/LineChartView/effice_picture/a.jpg";
String key = DiskLrucacheUtils.getKey(bitMapUrl);
Editor edit = mDiskLrucache.edit(key);
// 7.从服务器下载图片
boolean isSuccess = DiskLrucacheUtils.downloadBitmap(bitMapUrl,
edit.newOutputStream(0));
if (isSuccess) {
// 8.提交到缓存
edit.commit();
// 9.下载成功去展示图片
Message msg = mHandler.obtainMessage();
msg.obj = true;
mHandler.sendMessage(msg);
} else {
edit.abort();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
try {
if (mDiskLrucache != null) {
mDiskLrucache.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPause();
}
@Override
protected void onDestroy() {
try {
if (mDiskLrucache != null) {
mDiskLrucache.close();
}
} catch (IOException e) {
e.printStackTrace();
}
super.onDestroy();
}
}
使用DiskLrucache自己写的工具类.
package com.pangzaifei.disklrucachedemo.libcore;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;
/**
* diskLrucache的工具类
*
* @author pangzf
* @date 2014年8月12日 上午10:58:50
*/
public class DiskLrucacheUtils {
/**
* 获得缓存目录,当sdcard存在的时候使用,sdcard图片缓存,如果sdcard不存在使用data/data下的图片缓存
*
* @param context
* @param uniqueName
* @return
*/
public static File getDiskCache(Context context, String uniqueName) {
String path;
if (Environment.getExternalStorageDirectory().equals(
Environment.MEDIA_MOUNTED)) {
// 存在sdcard
path = Environment.getExternalStorageDirectory().getPath();
} else {
// 不存在sdcard使用手机内存
path = context.getCacheDir().getPath();
}
return new File(path + File.separator + uniqueName);
}
/**
* 获得app版本号
*
* @param context
* @return
* @throws NameNotFoundException
*/
public static int getAppVersion(Context context)
throws NameNotFoundException {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
return packageInfo.versionCode;
}
/**
* 将图片url进行md5加密生成一个字符串,因为有的url地址里面存在特殊字符
*
* @param urlStr
* @return
* @throws NoSuchAlgorithmException
*/
public static String getKey(String urlStr) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("md5");
messageDigest.update(urlStr.getBytes());
return bytesToString(messageDigest.digest());
}
/**
* byte转string
*
* @param bytes
*/
private static String bytesToString(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();
}
/**
* 下载图片到cache
*
* @param imageString
* @param ops
* @return
*/
public static boolean downloadBitmap(String imageString, OutputStream ops) {
URL url;
HttpURLConnection conn = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
url = new URL(imageString);
conn = (HttpURLConnection) url.openConnection();
bis = new BufferedInputStream(conn.getInputStream());
bos = new BufferedOutputStream(ops);
int b;
while ((b = bis.read()) != -1) {
bos.write(b);
}
return true;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.disconnect();
}
if (bos != null) {
bos.close();
}
if (bis != null) {
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
}
感谢guolin的博客对我的帮助。