安卓 : SoftReference/WeakReference example

标签 android weak-references soft-references

我的应用程序收到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/

相关文章:

java - 如何使用自己的应用程序在 Twitter 上发布推文

android - 远程内容不刷新

使用 Semaphoreci 进行 Android 自动化集成测试。如何正确设置?

java - WeakReference 是我需要的吗?

c# - 是否可以在不需要不安全上下文的情况下判断两个 WeakReference 是否指向 C# 中的同一个对象?

Java SoftReference 奇怪的行为

java - 有什么方法可以判断方法是否结束或本地方法不再使用?

android - 调整 EditText 大小以适合文本大小

java - 对包含嵌套强引用和垃圾收集的对象的弱引用

java - 在一个集合中混合不同的引用类型