三级缓存的使用框架

package liujianrui.bawei.com.three_level_buffer.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.ImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;


import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;

/**
 * Created by ASUS on 2017/3/23.
 */

   //这是一个工具类:可以自己封装,Mainactivity需要自己写,自己调用:
public class Bitmaputils {
//这是执行第一个网络,
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    ImageViewToBitmap imageViewToBitmap = (ImageViewToBitmap) msg.obj;
                    imageViewToBitmap.iv.setImageBitmap(imageViewToBitmap.bitmap);
                    Log.i("xxxxl",imageViewToBitmap.bitmap+"");
                    break;
            }
        }
    };
//软引用     根据键值获取Bitmap
    private Map<String, SoftReference<Bitmap>> map = new HashMap<String, SoftReference<Bitmap>>();
    //图片本地缓存路径
    String path= Environment.getExternalStorageDirectory()+"/imgache";
    File file=new File(path);
    Context context;
    public Bitmaputils(Context context) {
        this.context = context;
          if(!file.exists())
          {
              file.mkdirs();
          }
    }


    //加载图片的方法
    public void display(ImageView iv, String url) {
        //内存缓存

        Bitmap bitmap = loadMemory(url);
        if (bitmap != null) {
            iv.setImageBitmap(bitmap);
            Log.i("axxx",bitmap+"");
        } else {
            //sdcard缓存
            bitmap = loadSD(url);
            if (bitmap != null) {
                iv.setImageBitmap(bitmap);
                Log.i("xxxx",bitmap+"");
            } else {
                //网络缓存
                loadInternetImage(iv, url);

            }
        }


    }
    //获取网络图片
    private void loadInternetImage(ImageView iv, String url) {
        //开子线程做耗时操作
        new Thread(new DownloadImage(iv, url)).start();

    }
      private class DownloadImage implements Runnable{
          ImageView iv;
          String url;
          private FileOutputStream fileOutputStream;
          private InputStream inputStream;

          public DownloadImage(ImageView iv, String url) {
              this.iv = iv;
              this.url = url;
          }
          @Override
          public void run() {
              HttpClient clent = new DefaultHttpClient();
              HttpGet get = new HttpGet(url);
              try {
                  HttpResponse execute = clent.execute(get);
                  if(execute.getStatusLine().getStatusCode() == 200)
                  {
                      inputStream = execute.getEntity().getContent();
                      String name = getFileName(url);
                      File filename = new File(file, name);
                      fileOutputStream = new FileOutputStream(filename);
                      byte[] buffer = new byte[1024];
                      int len = 0;
                      while ((len = inputStream.read(buffer)) != -1) {
                          fileOutputStream.write(buffer, 0, len);
                      }

                      inputStream.close();
                      fileOutputStream.close();
                      //sdcard缓存
                      Bitmap bitmap = loadSD(url);
                      //ImageView转换成Bitmap转换成Bitmap
                      ImageViewToBitmap ivtb = new ImageViewToBitmap(iv, bitmap);
                      Message message = Message.obtain(handler, 0, ivtb);
                      message.sendToTarget();

                  }

              } catch (Exception e) {


                  e.printStackTrace();


              }
          }
      }
    //获取图片的名称
    private String getFileName(String url) {
        return Md5Utils.encode(url) + ".jpg";

    }




    //获取本地图片
    private Bitmap loadSD(String url) {
        String name = getFileName(url);
        File filename = new File(file, name);

        if (filename.exists()) {
            //BitmapFactory选项
            BitmapFactory.Options options = new BitmapFactory.Options();
            //加载图片宽高
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(name, options);
            //获取图片和手机屏幕宽高
            int outWidth = options.outWidth;
            int outHeight = options.outHeight;
            DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
            int widthPixels = displayMetrics.widthPixels;
            int heightPixels = displayMetrics.heightPixels;
            //图片跟手机屏幕进行比对
            int scale = 0;
            int scaleX = outWidth / widthPixels;
            int scaleY = outHeight / heightPixels;
            scale = scaleX > scaleY ? scaleX : scaleY;
            if (scale == 0) {
                scale = 1;
            }
            options.inJustDecodeBounds = false;
            options.inSampleSize = scale;
            Bitmap bitmap = BitmapFactory.decodeFile(filename.getAbsolutePath(), options);
            //内存缓存
            SoftReference<Bitmap> value = new SoftReference<Bitmap>(bitmap);
            map.put(name, value);
            return bitmap;



        }


        return null;

    }


    //ImageView转换成Bitmap转换成Bitmap
    private class ImageViewToBitmap {
        ImageView iv;
        Bitmap bitmap;

        public ImageViewToBitmap(ImageView iv, Bitmap bitmap) {
            this.iv = iv;
            this.bitmap = bitmap;
        }
    }

    //缓存到内存
    private Bitmap loadMemory(String url) {
        SoftReference<Bitmap> value = map.get(url);
        if (value != null) {
            Bitmap bitmap = value.get();
            return bitmap;
        }
        return null;

    }

 }

谨记需建一个类

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 (Exception e) {
            e.printStackTrace();
            //can't reach
            return "";
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值