android 缓存Bitmap 使用内存缓存
2016-03-25 16:09
615 查看
private LruCache<String, Bitmap> mMemoryCache;
/** * 判断内存大小 设置位图的缓存空间 */ private void judgeMemory() { final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); final int cacheSize = maxMemory / 8; mMemoryCache = new LruCache<String, Bitmap>(cacheSize) { @Override protected int sizeOf(String key, Bitmap bitmap) { return bitmap.getByteCount() / 1024; } }; }
/** * 将位图添加到缓存中 * * @param key key值 * @param bitmap 放入的位图 */ private void addBitmapToMemoryCache(String key, Bitmap bitmap) { if (getBitmapFromMemCache(key) == null) { mMemoryCache.put(key, bitmap); } }
/** * 从缓存中得到位图 * * @param key key值 * @return 返回取出的位图 */ private Bitmap getBitmapFromMemCache(String key) { return mMemoryCache.get(key); }
/** * 检索AsyncTask是否已经被分配到指定的ImageView: * * @param imageView 传入imageview控件 * @return 返回已经被分配指定的imageview */ private static BitmapWorkTask getBitmapWorkerTask(ImageView imageView) { if (imageView != null) { final Drawable drawable = imageView.getDrawable(); if (drawable instanceof AsyncDrawable) { final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable; return asyncDrawable.getBitmapWorkTask(); } } return null; }
/** * 创建一个专用的Drawable的子类来储存任务的引用。 */ class AsyncDrawable extends BitmapDrawable { private final WeakReference bitmapWorkerTaskReference; public AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkTask bitmapWorkTask) { super(res, bitmap); bitmapWorkerTaskReference = new WeakReference(bitmapWorkTask); } public BitmapWorkTask getBitmapWorkTask() { return (BitmapWorkTask) bitmapWorkerTaskReference.get(); } }
在doInBackground中添加到缓存
protected Bitmap doInBackground(Integer... integers) { final Bitmap bitmap = decodeSampleBitmapFromResources(getResources(), integers[0], 100, 100); addBitmapToMemoryCache(String.valueOf(integers[0]), bitmap); return bitmap; }
然后在oncreate中 加载,首先判断从缓存中加载。
if (bitmap != null) { imageView.setImageBitmap(bitmap); } else { final BitmapWorkTask task = new BitmapWorkTask(imageView); final AsyncDrawable asyncDrawable = new AsyncDrawable(getResources(), decodeSampleBitmapFromResources(getResources(), resId, imageView.getMaxWidth(), imageView.getMaxHeight()), task); imageView.setImageDrawable(asyncDrawable); task.execute(resId); }
相关文章推荐
- Android aidl Binder框架浅析
- [Android]static变量的生命周期
- android学习之intent跳转一
- Android的线程和线程池
- Android实现插件化(热加载)和插件加密
- 解决Android-PullToRefresh模块引用问题
- Android Binder设计与实现 - 设计篇
- Android 编译环境搭建
- Android中activity属性设置
- 每个Android开发者都应该了解的资源列表
- android线程浅析
- android学习之view的构造
- Java(Android)线程池
- LayoutInflater效率分析及源码跟踪
- Android布局优化之ViewStub、include、merge使用与源码分析 .
- Android总结(二)
- Android 手机QQ临时会话
- 创业公司求IOS、Android攻城狮一枚
- Android Universal Image Loader加载 ListView 滑动过程中图片显示重复错位闪烁问题
- Android处理图片OOM的若干方法小结