我创建了一个 ViewFlipper 以在单个活动中显示来自 Internet 的图像。投掷时,将图像设置为imageView,然后将其添加到viewflipper。但问题是,在显示大约 20 张图像后总是出现 OOM。我做了一些干净的工作来解决它,但它没有用!这是代码。
public class ImageCache {
static private ImageCache cache;
private Hashtable<Integer, MySoftRef> hashRefs;
private ReferenceQueue<Bitmap> q;
private class MySoftRef extends SoftReference<Bitmap> {
private Integer _key = 0;
public MySoftRef(Bitmap bmp, ReferenceQueue<Bitmap> q, int key) {
super(bmp, q);
_key = key;
}
}
public ImageCache() {
hashRefs = new Hashtable<Integer, MySoftRef>();
q = new ReferenceQueue<Bitmap>();
}
public static ImageCache getInstance() {
if (cache == null) {
cache = new ImageCache();
}
return cache;
}
private void addCacheBitmap(Bitmap bmp, Integer key) {
cleanCache();
MySoftRef ref = new MySoftRef(bmp, q, key);
hashRefs.put(key, ref);
}
public Bitmap getBitmap(int resId) {
Bitmap bmp = null;
if (hashRefs.containsKey(resId)) {
MySoftRef ref = (MySoftRef) hashRefs.get(resId);
bmp = (Bitmap) ref.get();
}
if (bmp == null) {
URL imgUrl = null;
try {
imgUrl = new URL("http:/example/images/" + resId
+ ".jpg");
HttpURLConnection conn = (HttpURLConnection) imgUrl
.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
bmp = BitmapFactory.decodeStream(is);
is.close();
addCacheBitmap(bmp, resId);
} catch (Exception e) {
e.printStackTrace();
}
}
return bmp;
}
private void cleanCache() {
MySoftRef ref = null;
while ((ref = (MySoftRef) q.poll()) != null) {
hashRefs.remove(ref._key);
}
}
public void clearCache() {
cleanCache();
hashRefs.clear();
System.gc();
System.runFinalization();
}
这是加载图像代码。
public void LoadImage(int n){
iv = new ImageView(this);
imageCache = new ImageCache();
Bitmap bm = imageCache.getBitmap(n);
iv.setImageBitmap(bm);
iv.setScaleType(ImageView.ScaleType.CENTER);
viewFlipper.addView(iv, new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
}