android 软引用使用
2016-03-28 16:21
351 查看
首先定义一个HashMap,保存软引用对象。
private Map<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();
再来定义一个方法,保存Bitmap的软引用到HashMap。
public void addBitmapToCache(String path) {
// 强引用的Bitmap对象
Bitmap bitmap = BitmapFactory.decodeFile(path);
// 软引用的Bitmap对象
SoftReference<Bitmap> softBitmap = new SoftReference<Bitmap>(bitmap);
// 添加该对象到Map中使其缓存
imageCache.put(path, softBitmap);
}
获取的时候,可以通过SoftReference的get()方法得到Bitmap对象。
public Bitmap getBitmapByPath(String path) {
// 从缓存中取软引用的Bitmap对象
SoftReference<Bitmap> softBitmap = imageCache.get(path);
// 判断是否存在软引用
if (softBitmap == null) {
return null;
}
// 取出Bitmap对象,如果由于内存不足Bitmap被回收,将取得空
Bitmap bitmap = softBitmap.get();
return bitmap;
}
private Map<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();
再来定义一个方法,保存Bitmap的软引用到HashMap。
public void addBitmapToCache(String path) {
// 强引用的Bitmap对象
Bitmap bitmap = BitmapFactory.decodeFile(path);
// 软引用的Bitmap对象
SoftReference<Bitmap> softBitmap = new SoftReference<Bitmap>(bitmap);
// 添加该对象到Map中使其缓存
imageCache.put(path, softBitmap);
}
获取的时候,可以通过SoftReference的get()方法得到Bitmap对象。
public Bitmap getBitmapByPath(String path) {
// 从缓存中取软引用的Bitmap对象
SoftReference<Bitmap> softBitmap = imageCache.get(path);
// 判断是否存在软引用
if (softBitmap == null) {
return null;
}
// 取出Bitmap对象,如果由于内存不足Bitmap被回收,将取得空
Bitmap bitmap = softBitmap.get();
return bitmap;
}
相关文章推荐
- 【项目篇】Android团队项目开发之统一代码规范
- android native ndk崩溃定位
- Android 异步消息处理机制 让你深入理解 Looper、Handler、Message三者关系
- List集合数据排序
- android listview的单选事件
- android 权限明细
- android studio 在win10上弹出框过大,无法进行下一步
- WindowManager addView不上去的问题?
- android studio 子工程模块编译可以通过,运行时却找不道子工程包名解决
- Android 通知栏Notification的整合 全面学习
- AOSP sourcecode 使用Android Studio打开
- android中activity的生命周期
- Android5.0+(CollapsingToolbarLayout)
- Android 疑难杂症之获取listView Item上面组件的值
- android属性动画常用方法总结
- android自定义加载数据动画dialog和简单的timer计时器
- Android_关于屏幕适配经验总结
- 【Android】沉浸式状态栏实现
- Android判断同一个类的两个对象的内容是否相同
- Failed to resolve: com.android.support:support-v4:23.1.1