gpt4 book ai didi

机器人 : SoftReference/WeakReference example

转载 作者:搜寻专家 更新时间:2023-11-01 08:14:03 25 4
gpt4 key购买 nike

我的应用程序出现了 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com