我的应用程序收到OutOfMemoryError
。当我浏览一些教程时,我开始知道,我可以使用Softreference/Weakreference
来解决这个问题。但我不知道如何使用Softreference/Weakreference
。
请向我推荐一些提供软引用或弱引用示例的教程。
谢谢...
最佳答案
package com.myapp;
import java.io.File;
import java.lang.ref.SoftReference;
import java.util.WeakHashMap;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
public class BitmapSoftRefrences {
public static String SDPATH = Environment.getExternalStorageDirectory()
+ "/MYAPP";
// 1. create a cache map
public static WeakHashMap<String, SoftReference<Bitmap>> mCache = new WeakHashMap<String, SoftReference<Bitmap>>();
public static String TAG = "BitmapSoftRefrences";
// 2. ask for bitmap
public static Bitmap get(String key) {
if (key == null) {
return null;
}
try {
if (mCache.containsKey(key)) {
SoftReference<Bitmap> reference = mCache.get(key);
Bitmap bitmap = reference.get();
if (bitmap != null) {
return bitmap;
}
return decodeFile(key);
}
} catch (Exception e) {
// TODO: handle exception
Logger.debug(BitmapSoftRefrences.class,
"EXCEPTION: " + e.getMessage());
}
// the key does not exists so it could be that the
// file is not downloaded or decoded yet...
File file = new File(SDPATH + "/" + key);
if (file.exists()) {
return decodeFile(key);
} else {
Logger.debug(BitmapSoftRefrences.class, "RuntimeException");
throw new RuntimeException("RuntimeException!");
}
}
// 3. the decode file will return bitmap if bitmap is not cached
public static Bitmap decodeFile(String key) {
// --- prevent scaling
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inScaled = false;
Bitmap bitmap = BitmapFactory.decodeFile(SDPATH + "/" + key, opt);
mCache.put(key, new SoftReference<Bitmap>(bitmap));
return bitmap;
}
public static void clear() {
mCache.clear();
}
}
关于安卓 : SoftReference/WeakReference example,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6533006/