我正在尝试为 Android 创建缓存图像系统,但内存消耗只会越来越大。我通过 Android网站查看了一些想法,但问题只是不想消失。
下面是我从 SD 卡获取图像、设置它并随后销毁的代码。我究竟做错了什么?
WeakReference<Bitmap> newImageRef;
public void setImageFromFile(File source){
if(source.exists()){
Bitmap newImage = BitmapFactory.decodeFile(source.getAbsolutePath());
newImageRef = new WeakReference<Bitmap>(newImage);
if(newImage != null){
this.setImageBitmap(newImage);
}
}
}
@Override
protected void onDetachedFromWindow() {
Bitmap newImage = newImageRef.get();
if (newImage != null) {
newImage.recycle();
newImage = null;
}
Drawable drawable = getDrawable();
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
if (bitmap != null){
bitmap.recycle();
}
}
this.setImageResource(0);
newImage = null;
newImageRef = null;
System.gc();
super.onDetachedFromWindow();
}