一、软引用的垃圾回收SoftReference
对象的软引用。
如果一个对象具有软引用,内存空间足够,垃圾回收器就不会回收它;
如果内存空间不足了,就会回收这些对象的内存。
只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可用来实现内存敏感的高速缓存。使用软引用能防止内存泄露,增强程序的健壮性。
SoftReference的特点是它的一个实例保存对一个Java对象的软引用,该软引用的存在不妨碍垃圾收集线程对该Java对象的回收。
案例:
(1)用Map集合缓存软引用的Bitmap对象
Map<String, SoftReference<Bitmap>> imageCache = new new HashMap<String, SoftReference<Bitmap>>();
//强引用的Bitmap对象
Bitmap bitmap = BitmapFactory.decodeStream(InputStream);
//软引用的Bitmap对象
SoftReference<Bitmap> bitmapcache = new SoftReference<Bitmap>(bitmap);
//添加该对象到Map中使其缓存
imageCache.put("1",softRbitmap);
(2)从缓存中取软引用的Bitmap对象
SoftReference<Bitmap> bitmapcache_ = imageCache.get("1");
//取出Bitmap对象,如果由于内存不足Bitmap被回收,将取得空
Bitmap bitmap_ = bitmapcache_.get();
2、批量保存图片
public Map<String, SoftReference<Bitmap>> mAvatarCache = new HashMap<String, SoftReference<Bitmap>>();
public Bitmap getAvatar(String imageName) {
if (mAvatarCache.containsKey(imageName)) {
Reference<Bitmap> reference = mAvatarCache.get(imageName);
if (reference.get() == null || reference.get().isRecycled()) {
mAvatarCache.remove(imageName);
} else {
return reference.get();
}
}
InputStream is = null;
Bitmap bitmap = null;
try {
//根据方言来获取本地文件(以流的方式来存放)
is = getAssets().open(AVATAR_DIR + imageName);
bitmap = BitmapFactory.decodeStream(is);
if (bitmap == null) {
throw new FileNotFoundException(imageName + "is not find");
}
mAvatarCache.put(imageName, new SoftReference<Bitmap>(bitmap));
return bitmap;
} catch (Exception e) {
return mDefaultAvatar;
} finally {
try {
if (is != null) {
is.close();
is = null;
}
} catch (IOException e) {
}
}
}
二、图片资源存放位置的改变:
bitmap的存放位置根据Android版本的不同真的有所不同。好了,下面就是找出怎么把图片存放到native heap里就行了,
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Config.ARGB_8888;
options.inPurgeable = true;// 允许可清除
options.inInputShareable = true;// 以上options的两个属性必须联合使用才会有效果
String sname = String.format( “xxx.png”, sTowerStyle, j, sDirction, i);
InputStream is = am.open(sname);
arrBmp[ iBmpIndex] = BitmapFactory .decodeStream(is, null, options);