Developer cannot guess when Java GC is run. So, in Android, Bitmap class has special interface 'recycle' to reuse memory as soon as possible when Bitmap is not used anymore.
Based on similar reason, we need to recycle ImageView.
But, here are some points to consider when recycling memory of ImageView.
* ImageView has drawable - most case it is instance of BitmapDrawable - regardless of it's input-resource-type - ex setImageResource(), setImageURI() or setImageBitmap(). And, ImageView has BitmapDrawable not only the case of setImageBitmap but also some other cases - ex setImageResource.
* Sample code to recycle Bitmap of ImageView is something like below
// true == (v instanceof ImageView)
Drawable d = v.getDrawable();
if (d instanceof BitmapDrawable) { // to make sure.
BitmapDrawable bmd = (BitmapDrawable)drawable;
Bitmap bitmap = bmd.getBitmap();
bitmap.recycle();
}
* setImageDrawable(), setImageResource() and setImageURI() compares new-input and current used one.
So, if new one is same with current one, ImageView doesn't do anything. (See ImageView.java for details.)
* ImageView doesn't provide any interface to compare that given one is same with current one or not.
Because of above 4 reasons, recycling memory of ImageView is not straight-forward.
Simplest way, in my opinion, is feed newly-created-Bitmap-instance to ImageView whenever changing drawable, and recycle old one.
Because drawable is newly-created-instance, we don't need to compare new one with old one.
So, blind recycling old one, is ok in this case.
Here is sample function.
public static void
setThumbnailImageView(ImageView v, byte[] imgdata) {
Bitmap thumbnailBm;
if (null != imgdata && imgdata.length > 0)
thumbnailBm = BitmapFactory.decodeByteArray(imgdata, 0, imgdata.length);
else
thumbnailBm = BitmapFactory.decodeResource(Utils.getAppContext().getResources(),
R.drawable.ic_unknown_image);
// Recycle old Bitmap
Drawable drawable = v.getDrawable();
if (drawable instanceof BitmapDrawable) { // to make sure.
BitmapDrawable bmd = (BitmapDrawable)drawable;
Bitmap bitmap = bmd.getBitmap();
bitmap.recycle();
}
// change to new one.
v.setImageBitmap(thumbnailBm);
}
'Domain > Android' 카테고리의 다른 글
[Android] Issue regarding android:targetSdkVersion. (0) | 2012.10.08 |
---|---|
Policy of Google Play to consider registering App to Android Google Play. (0) | 2012.10.04 |
[Android] Developing Android-native-library on 64bit build machine (0) | 2011.09.15 |
[Android] Creating minimum set of Android (Kernel + adbd + ueventd) for Android kernel test. (0) | 2011.05.31 |
[Android] Managing service... (0) | 2011.05.02 |