当前位置: 移动技术网 > 移动技术>移动开发>Android > Android 图片的三级缓存机制实例分析

Android 图片的三级缓存机制实例分析

2019年07月24日  | 移动技术网移动技术  | 我要评论

android 图片的三级缓存机制实例分析

当我们获取图片的时候,如果不加以协调好图片的缓存,就会造成大流量,费流量应用,用户体验不好,影响后期发展。为此,我特地分享android图片的三级缓存机制之从网络中获取图片,来优化应用,具体分三步进行:

(1)从缓存中获取图片
(2)从本地的缓存目录中获取图片,并且获取到之后,放到缓存中
(3)从网络去下载图片,下载完成之后,保存到本地和放到缓存中

很好的协调这三层图片缓存就可以大幅度提升应用的性能和用户体验。

快速实现三级缓存的工具类imagecacheutil如下(有更好的建议可以发我的邮箱说出你的想法,一起完善,邮箱见博客主页“给我写信”):

1.从网络中获取图片的三级缓存工具类imagecacheutil

public class imagecacheutil {
  private lrucache<string, bitmap> lrucache;
  private file cachedir;
  private executorservice newfixedthreadpool;
  private handler handler;
  public static final int success = 100;
  public static final int fail = 101;
  //当我们获取图片的时候,分三步
  //1.从缓存中获取图片
  //2.从本地的缓存目录中获取图片,并且获取到之后,放到缓存中
  //3.从网络去下载图片,下载完成之后,保存到本地缓存目录和放到缓存中
  public imagecacheutil(context context,handler handler){
    //获取缓存的大小
    int maxsize = (int) (runtime.getruntime().maxmemory()/8);
    //maxsize : 设置缓存的最大空间
    lrucache = new lrucache<string, bitmap>(maxsize){
      //获取移出的图片所占用的空间,当图片移出的时候,需要将图片占用的缓存空间从缓存中移出
       @override
      protected int sizeof(string key, bitmap value) {
         //计算图片所占用的缓存大小
         //getrowbytes : 获取图片一行所占用的大小
         //getheight : 获取图片所占用行数
        return value.getrowbytes()*value.getheight();
      }
    };
    //获取缓存目录
    cachedir = context.getcachedir();
    //获取线程池
    //nthreads : 线程池中的线程数量
    newfixedthreadpool = executors.newfixedthreadpool(5);
    this.handler = handler;
  }
  /**
   * 获取图片的方法
   * @param url
   * @param positon
   * @return
   */
  public bitmap getbitmap(string url,int position){
    bitmap bitmap = null;
    //1.从缓存中获取图片 (lrucache<k,v>) k:key 保存图片的标示,一般都是图片的url地址,v:value 图片
    bitmap = lrucache.get(url);//根据key从缓存中获取相应的图片
    //lrucache.put(url, bitmap):保存图片到缓存中
    if (bitmap!=null) {
      return bitmap;
    }
    //2.从本地的缓存目录中获取图片,并且获取到之后,放到缓存中
    bitmap = getfromlocal(url);
    if (bitmap!=null) {
      return bitmap;
    }
    //3.从网络去下载图片,下载完成之后,保存到本地缓存目录和放到缓存中
    getfromnet(url,position);
    return null;
  }
  /**
   * 从网络下载图片,异步方式,线程池
   * @param url
   * @param position
   */
  private void getfromnet(string url, int position) {
    newfixedthreadpool.execute(new runnabletask(url,position));
  }
  class runnabletask implements runnable{
    private string imageurl;
    private int position;
    public runnabletask(string url,int position){
      this.imageurl = url;
      this.position = position;
    }

    @override
    public void run() {
      message message = message.obtain();
      //下载图片
      try {
        url url = new url(imageurl);
        httpurlconnection conn = (httpurlconnection) url.openconnection();
        conn.setreadtimeout(3000);
        conn.setconnecttimeout(5000);
        conn.setrequestmethod("get");
        inputstream inputstream = conn.getinputstream();
        bitmap bitmap = bitmapfactory.decodestream(inputstream);
        //保存到本地缓存中
        wirtetolocal(imageurl, bitmap);
        //保存到系统缓冲中
        lrucache.put(imageurl, bitmap);
        //显示图片,给handler发送消息
        message.what = success;
        message.obj = bitmap;
        message.arg1 = position;
        handler.sendmessage(message);
        return;
      } catch (exception e) {
        e.printstacktrace();
      }
      message.what = fail;
      handler.sendmessage(message);
    }
  }
  /**
   * 从本地缓存目录获取图片
   * @param url
   */
  private bitmap getfromlocal(string url) {
    //根据图片的名称获取图片
    try {
      string filename = md5encoder.encode(url).substring(10);
      file file = new file(cachedir, filename);
      bitmap bitmap = bitmapfactory.decodefile(file.getabsolutepath());
      //防盗缓存当中
      lrucache.put(url, bitmap);
      return bitmap;
    } catch (exception e) {
      e.printstacktrace();
    }
    return null;
  }
  /**
   * 将图片保存到本地缓存目录中
   */
  public void wirtetolocal(string url,bitmap bitmap){
    //url名称,通过md5加密,并且截取前10位作为名称
    try {
      string filename = md5encoder.encode(url).substring(10);
      file file = new file(cachedir, filename);
      fileoutputstream out = new fileoutputstream(file);
      //format :图片的格式(android中用的png多,因为png质量是不会改变的)
      //quality : 压缩比例
      //stream : 流信息
      bitmap.compress(compressformat.jpeg, 100, out);//将图片保存到那个位置
    } catch (exception e) {
      e.printstacktrace();
    }
  }

}

其中用到的md5encoder类如下:

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();
  }
}

2.在mainactivity初始化imagecacheutil

imagecacheutil imagecacheutil = new imagecacheutil(getapplicationcontext, handler);

3.在mainactivity中通过handler将图片显示出来

图片通过工具类下载成功之后,不仅要将图片保存到本地缓存中和系统缓存中,还要将图片显示出来,通过handler进行处理,这个handler是设置使用imagecacheutil工具类,就要把你的handler传递过来,方便我们传消息给相应使用imagecacheutil工具类的类进行处理。

private handler handler = new handler(){
  public void handlemessage(android.os.message msg) {
    switch (msg.what) {
    case imagecacheutil.success:
      //给控件设置图片
      bitmap bitmap = (bitmap) msg.obj;
      int position = msg.arg1;
      imageview image= (imageview) view.findviewwithtag(position);//就是根据条目的位置获取相应的控件
      if (image != null && bitmap != null) {
        image.setimagebitmap(bitmap);
      }
      break;
    case imagecacheutil.fail:
      toast.maketext(getapplicationcontext, "图片下载失败", 0).show();
      break;
    }
  };
};

4.在mainactivity中的adapter的getview中进行调用

bitmap bitmap = imagecacheutil.getbitmap(list.get(position).listimage, position);
if (bitmap != null) {
  viewhodler.image.setimagebitmap(bitmap);
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网