上篇博客是初级版:http://blog.youkuaiyun.com/sunzhi_/article/details/78482345
这次用的是线程池和Lrucahe详细请看代码
package com.bawei.threecache.Utils;
/**
* 1. 类的用途 LruCache ExecutorService线程池
* 2. @author forever
* 3. @date 2017/4/11 13:25
*/
public class ImageUtils {
//上下下方
private Context context;
//图片本地缓存地址
private final static String CACHE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/imagecache";
//图片缓存目录
File cacheDir = new File(CACHE_DIR);
//图片内存缓存所占用的内存大小
int maxSize = (int) (Runtime.getRuntime().maxMemory() / 8);
private LruCache<String, Bitmap> images = new LruCache<String, Bitmap>(maxSize) {
//返回Bitmap的大小
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
};
private final ExecutorService executorService;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
ImageViewBitmap imageViewBitmap = (ImageViewBitmap) msg.obj;
imageViewBitmap.imageView.setImageBitmap(imageViewBitmap.bitmap);
break;
}
}
};
public ImageUtils(Context context) {
this.context = context;
if (!cacheDir.exists()) {
//创建
cacheDir.mkdirs();
}
//创建线程池
executorService = Executors.newFixedThreadPool(5);
}
public void display(ImageView imageView, String path) {
//内存缓存
Bitmap bitmap = loadMemary(path);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
//sdcard缓存
bitmap = loadSD(path);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
//网络缓存
loadInternet(imageView, path);
}
}
}
private Bitmap loadMemary(String path) {
Bitmap bitmap = images.get(path);
return bitmap;
}
//加载本地图片
private Bitmap loadSD(String path) {
String name = getFileName(path);
File file = new File(cacheDir, name);
if (file.exists()) {
BitmapFactory.Options options = new BitmapFactory.Options();
//加载图片边框 不加载内容
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), options);
//设置缩放比例
int inSimpleSize = inSimpleSize(options);
options.inJustDecodeBounds = false;
options.inSampleSize = inSimpleSize;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
//LruCache 存在内存
images.put(path, bitmap);
return bitmap;
}
return null;
}
private int inSimpleSize(BitmapFactory.Options options) {
int outWidth = options.outWidth;
int outHeight = options.outHeight;
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int widthPixels = displayMetrics.widthPixels;
int heightPixels = displayMetrics.heightPixels;
//计算缩放比例
int scaleX = outWidth / widthPixels;
int scaleY = outHeight / heightPixels;
int simpleSize = scaleX > scaleY ? scaleX : scaleY;
if (simpleSize == 0) {
simpleSize = 1;
}
return simpleSize;
}
//加载网络图片
private void loadInternet(ImageView imageView, String path) {
//把任务提交给线程池
executorService.submit(new DownloadBitmapTask(imageView, path));
}
private class DownloadBitmapTask implements Runnable {
ImageView imageView;
String path;
private InputStream inputStream;
private FileOutputStream fos;
public DownloadBitmapTask(ImageView imageView, String path) {
this.imageView = imageView;
this.path = path;
}
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == 200) {
inputStream = connection.getInputStream();
//得到图片名字
String name = getFileName(path);
//图片地址
File file = new File(cacheDir, name);
fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
//把图片缓存到本地
fos.write(buffer, 0, len);
}
Bitmap bitmap = loadSD(path);
//把ImageView和Bitmap进行转换
ImageViewBitmap imageViewBitmap = new ImageViewBitmap(imageView, bitmap);
Message message = handler.obtainMessage(0, imageViewBitmap);
message.sendToTarget();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private class ImageViewBitmap {
ImageView imageView;
Bitmap bitmap;
public ImageViewBitmap(ImageView imageView, Bitmap bitmap) {
this.imageView = imageView;
this.bitmap = bitmap;
}
}
//得到图片名字
private String getFileName(String path) {
return path.substring(path.lastIndexOf("/") + 1);
}
}
package com.bawei.threecache.Utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Md5Utils {
public static String encode(String password){
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] result = digest.digest(password.getBytes());
StringBuffer sb = new StringBuffer();
for(byte b : result){
int number = (int)(b & 0xff) ;
String str = Integer.toHexString(number);
if(str.length()==1){
sb.append("0");
}
sb.append(str);
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
//can't reach
return "";
}
}
}