Android实现图片异步请求加三级缓存

2019-12-10 19:05:45于海丽


最后一级缓存 本地缓存 把网络下载的图片 文件名以MD5的形式保存到内存卡的制定目录

/**
 * 本地缓存工具类
 * 
 * @author Ace
 * @date 2016-02-19
 */
public class LocalCacheUtils {

 // 图片缓存的文件夹
 public static final String DIR_PATH = Environment
   .getExternalStorageDirectory().getAbsolutePath()
   + "/ace_bitmap_cache";

 public Bitmap getBitmapFromLocal(String url) {
  try {
   File file = new File(DIR_PATH, MD5Encoder.encode(url));

   if (file.exists()) {
    Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(
      file));
    return bitmap;
   }

  } catch (Exception e) {
   e.printStackTrace();
  }

  return null;
 }

 public void setBitmapToLocal(Bitmap bitmap, String url) {
  File dirFile = new File(DIR_PATH);

  // 创建文件夹 文件夹不存在或者它不是文件夹 则创建一个文件夹.mkdirs,mkdir的区别在于假如文件夹有好几层路径的话,前者会创建缺失的父目录 后者不会创建这些父目录
  if (!dirFile.exists() || !dirFile.isDirectory()) {
   dirFile.mkdirs();
  }

  try {
   File file = new File(DIR_PATH, MD5Encoder.encode(url));
   // 将图片压缩保存在本地,参1:压缩格式;参2:压缩质量(0-100);参3:输出流
   bitmap.compress(CompressFormat.JPEG, 100,
     new FileOutputStream(file));
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

MD5Encoder 

import java.security.MessageDigest;

public class MD5Encoder {
 
 public static String encode(String string) throws Exception {
  byte[] hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
  StringBuilder hex = new StringBuilder(hash.length * 2);
  for (byte b : hash) {
   if ((b & 0xFF) < 0x10) {
    hex.append("0");
   }
   hex.append(Integer.toHexString(b & 0xFF));
  }
  return hex.toString();
 }
}

最后新建一个工具类来使用我们上面的三个缓存方法

/**
 * 三级缓存工具类
 * 
 * @author Ace
 * @date 2016-02-19
 */
public class MyBitmapUtils {

 // 网络缓存工具类
 private NetCacheUtils mNetUtils;
 // 本地缓存工具类
 private LocalCacheUtils mLocalUtils;
 // 内存缓存工具类
 private MemoryCacheUtils mMemoryUtils;

 public MyBitmapUtils() {
  mMemoryUtils = new MemoryCacheUtils();
  mLocalUtils = new LocalCacheUtils();
  mNetUtils = new NetCacheUtils(mLocalUtils, mMemoryUtils);
 }

 public void display(ImageView imageView, String url) {
  // 设置默认加载图片
  imageView.setImageResource(R.drawable.news_pic_default);

  // 先从内存缓存加载
  Bitmap bitmap = mMemoryUtils.getBitmapFromMemory(url);
  if (bitmap != null) {
   imageView.setImageBitmap(bitmap);
   System.out.println("从内存读取图片啦...");
   return;
  }

  // 再从本地缓存加载
  bitmap = mLocalUtils.getBitmapFromLocal(url);
  if (bitmap != null) {
   imageView.setImageBitmap(bitmap);
   System.out.println("从本地读取图片啦...");
   // 给内存设置图片
   mMemoryUtils.setBitmapToMemory(url, bitmap);
   return;
  }

  // 从网络缓存加载
  mNetUtils.getBitmapFromNet(imageView, url);
 }

}