android - 如何防止LRU缓存android中的内存不足错误

标签 android caching lru image-caching android-lru-cache

我在我的 Android 应用程序中使用内存 LRU 缓存来缓存位图。但是在将一些位图加载到 LRU 映射中后,应用程序强制关闭并提示内存不足异常。我花了一整天的时间,但还没有找到解决方案,请任何人都可以帮助我,我严重陷入这个问题。提前致谢。

这是我的代码

final int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
final int cacheSize = maxMemory / 8;
bitmapHashMap = new LruCache<String, Bitmap>(cacheSize)
{
@SuppressLint("NewApi")
@Override
protected int sizeOf(String key, Bitmap value)
{
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2)
{
return value.getByteCount()/1024;
}
else
{
return (value.getRowBytes() * value.getHeight())/1024;
}
}
};

最佳答案

如果您的应用使用 android:largeheap="true",

永远不要使用Runtime.getRuntime().maxMemory(),因为您很可能会使用比可用内存更多的内存,并且更频繁地出现 OOM,而是使用内存类并计算缓存的大小,如下所示:

    /** Default proportion of available heap to use for the cache */
    final int DEFAULT_CACHE_SIZE_PROPORTION = 8;

    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    int memoryClass = manager.getMemoryClass();
    int memoryClassInKilobytes = memoryClass * 1024;
    int cacheSize = memoryClassInKilobytes / DEFAULT_CACHE_SIZE_PROPORTION;
    bitmapHashMap = new LruCache<String, Bitmap>(cacheSize)

关于android - 如何防止LRU缓存android中的内存不足错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21912560/

相关文章:

node.js - Node.js 中的 LRU 缓存

android - 获取 fragment 宽度,viewtreeobserver 监听器不工作

android - 如何在 android 中使用 Jackson 解析 json 响应?

caching - Amazon S3 和 Cloudfront 缓存,如何清除缓存或同步其缓存

iphone - iOS+ Parse.com : kPFCachePolicyCacheThenNetwork, 两次获取数据

algorithm - 最近最少使用 (LRU) 分页算法总是比 FIFO 更有效?

android - 如何检查手机上的响应式用户界面?

java - 切换不持续

drupal - Varnish 缓存 - 如何仅为主页清除/删除缓存

python - Lru_cache(来自 functools)如何工作?