三级缓存加强版

上篇博客是初级版:http://blog.csdn.net/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 "";
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值