【问题标题】:Android LRU Cache out of memory errorAndroid LRU 缓存内存不足错误
【发布时间】:2014-12-30 09:44:40
【问题描述】:

我正在使用 LRu 缓存从 http 协议下载和显示图像。我的应用是一个有 5 个片段的 Activity。每个片段加载一个带有图像和文本的自定义 ListView。

我的应用程序总是在一段时间后崩溃。

这是我的 LogCat:

11-03 18:00:22.613:E/dalvikvm-heap(1558):为进程生成 hprof:com.example.example PID:1558 11-03 18:00:24.004: E/dalvikvm(1558): 无法打开 /data/misc/app_oom.hprof: 权限被拒绝 11-03 18:00:24.064:E/dalvikvm-heap(1558):hprofDumpHeap 失败,结果:-1 11-03 18:00:24.064: E/dalvikvm-heap(1558): 在 hprofDumpHeap 之后进行进程 11-03 18:00:24.064:E/dalvikvm(1558):内存不足:堆大小=196608KB,分配=193561KB,限制=196608KB,过程限制=196608KB 11-03 18:00:24.064:E/dalvikvm(1558):额外信息:足迹=196552KB,允许的足迹=196608KB,修剪=12KB

这是我的 LRU 课程:

public class NBitmapCache extends LruCache<String, Bitmap>
implements ImageCache{
public NBitmapCache(int maxSize) {
    super(maxSize);
}

public NBitmapCache(Context ctx) {
    this(getCacheSize(ctx));
}

@Override
protected int sizeOf(String key, Bitmap value) {
    return value.getRowBytes() * value.getHeight();
}

@Override
public Bitmap getBitmap(String url) {
    return get(url);
}

@Override
public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
}

// Returns a cache size equal to approximately three screens worth of images.
public static int getCacheSize(Context ctx) {
    final DisplayMetrics displayMetrics = ctx.getResources().
            getDisplayMetrics();
    final int screenWidth = displayMetrics.widthPixels;
    final int screenHeight = displayMetrics.heightPixels;
    // 4 bytes per pixel
    final int screenBytes = screenWidth * screenHeight * 4;

    return screenBytes * 3;
}

}

我在这个论坛和谷歌搜索了如何解决这个问题,但我没有完成解决它。任何人都可以帮助我吗?我的应用程序的目标来自 sdk 8。

提前致谢。

【问题讨论】:

  • 我认为这与位图的回收有关 - 见Bitmap.recycle()
  • 我不明白如何在我的课堂上实现这个方法。谁能帮帮我?

标签: android bitmap out-of-memory android-lru-cache


【解决方案1】:

尝试计算应用程序可用的最大内存。并根据需要使用内存量。 你可以试试这个方法

final int maxMemory = (int)(Runtime.getRuntime().maxMemory() /1024);

【讨论】:

    猜你喜欢
    • 2014-03-21
    • 2013-01-17
    • 2012-03-07
    • 2013-11-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 2013-01-17
    相关资源
    最近更新 更多