图片三级缓存

图片三级缓存

  • 内存缓存,最优先从内存加载,速度快+无流量
  • 本地缓存,其次从本地加载,速度快+无流量
  • 网络缓存,最后才从网络加载,速度慢+耗流量

内存溢出

android默认给每个APP只分配16M内存(根据真机有相关浮动)

java引用方式

  • 强引用 Person a = new Person();
  • 软引用 SoftReference 较弱
  • 弱引用 WeakReference 其次弱
  • 虚引用 PhantomReferences 引用最弱

当内存不够时,垃圾回收器除了回收一些没有引用的对象之外,也会回收引用不强的对象。

写图片的三级缓存

  • 网络缓存类使用AsyncTask异步类处理,重点是内存缓存类,内存缓存中不能用HashMap类来写, 因为这样会涉及内存的溢出(oom)的问题。同时用软引用的话由于API level 9 之后垃圾回收机制对软引用对象的回收率更高了,所以已经不适合用软引用, 重用效果不好。但是可以用LruCache类 这用最近最久未使用方法来回收对象。更适合于对缓存的书写。
  • 其实最适合的是用XUtils类,别人写的已经很好了!

首先是要写一个缓存类:

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

}

网络缓存类:

public class NetCacheUtils {

    private LocalCacheUtils mLocalUtils;
    private MemoryCacheUtils mMemoryUtils;

    public NetCacheUtils(LocalCacheUtils localUtils,
            MemoryCacheUtils memoryUtils) {
        mLocalUtils = localUtils;
        mMemoryUtils = memoryUtils;
    }

    public void getBitmapFromNet(ImageView imageView, String url) {
        BitmapTask task = new BitmapTask();
        task.execute(imageView, url);
    }

    /**
     * AsyncTask是线程池+handler的封装 第一个泛型: 传参的参数类型类型(和doInBackground一致) 第二个泛型:
     * 更新进度的参数类型(和onProgressUpdate一致) 第三个泛型: 返回结果的参数类型(和onPostExecute一致,
     * 和doInBackground返回类型一致)
     */
    class BitmapTask extends AsyncTask<Object, Integer, Bitmap> {

        private ImageView mImageView;
        private String url;

        // 主线程运行, 预加载
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        // 子线程运行, 异步加载逻辑在此方法中处理
        @Override
        protected Bitmap doInBackground(Object... params) {
            mImageView = (ImageView) params[0];
            url = (String) params[1];
            mImageView.setTag(url);// 将imageView和url绑定在一起
            // publishProgress(values)//通知进度

            // 下载图片
            return download(url);
        }

        // 主线程运行, 更新进度
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        // 主线程运行, 更新主界面
        @Override
        protected void onPostExecute(Bitmap result) {
            if (result != null) {
                // 判断当前图片是否就是imageView要的图片, 防止listview重用导致的图片错乱的情况出现
                String bindUrl = (String) mImageView.getTag();
                if (bindUrl.equals(url)) {
                    // 给imageView设置图片
                    mImageView.setImageBitmap(result);
                    System.out.println("网络下载图片成功!");

                    // 将图片保存在本地
                    mLocalUtils.setBitmapToLocal(result, url);

                    // 将图片保存在内存
                    mMemoryUtils.setBitmapToMemory(url, result);
                }
            }
        }

    }

    /**
     * 下载图片
     * 
     * @param url
     */
    public Bitmap download(String url) {
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) (new URL(url).openConnection());

            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setRequestMethod("GET");

            conn.connect();

            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                InputStream in = conn.getInputStream();
                // 将流转化为bitmap对象
                Bitmap bitmap = BitmapFactory.decodeStream(in);
                return bitmap;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        return null;
    }

}

本地缓存类:

public class LocalCacheUtils {

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

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

        // 创建文件夹
        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();
        }
    }

}

内存缓存类:

public class MemoryCacheUtils {

    // private HashMap<String, SoftReference<Bitmap>> mMemroyCache = new
    // HashMap<String, SoftReference<Bitmap>>();
    // Android 2.3 (API Level
    // 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的对象,这让软引用和弱引用变得不再可靠,建议用LruCache
    private LruCache<String, Bitmap> mCache;

    public MemoryCacheUtils() {
        int maxMemory = (int) Runtime.getRuntime().maxMemory();// 获取虚拟机分配的最大内存
                                                                // 16M
        // LRU 最近最少使用, 通过控制内存不要超过最大值(由开发者指定), 来解决内存溢出
        mCache = new LruCache<String, Bitmap>(maxMemory / 8) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                // 计算一个bitmap的大小
                int size = value.getRowBytes() * value.getHeight();// 每一行的字节数乘以高度
                return size;
            }
        };
    }

    public Bitmap getBitmapFromMemory(String url) {
        // SoftReference<Bitmap> softReference = mMemroyCache.get(url);
        // if (softReference != null) {
        // Bitmap bitmap = softReference.get();
        // return bitmap;
        // }
        return mCache.get(url);
    }

    public void setBitmapToMemory(String url, Bitmap bitmap) {
        // SoftReference<Bitmap> soft = new SoftReference<Bitmap>(bitmap);
        // mMemroyCache.put(url, soft);
        mCache.put(url, bitmap);
    }

}

MD5相关类:

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();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值