如何防止LRU缓存android中的内存不足错误 [英] How to prevent Out of memory error in LRU Caching android

查看:91
本文介绍了如何防止LRU缓存android中的内存不足错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Memory LRU Caching在我的android应用程序中缓存位图,但是在将某些位图加载到LRU map应用后,强制关闭说内存不足异常.我花了整整一整天的时间来解决这个问题,但仍未找到解决方案,请任何人可以帮助我,我对此问题一无所知.

I have used Memory LRU Caching for caching bitmaps in my android application.but after some of the bitmaps are loaded into LRU map app force closes saying out of memory exception. I have spent whole day behind this but yet not found the solution please anyone can help me out I am badly stuck in this problem.Thanks in advance.

这是我的密码

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",

If your app uses android:largeheap="true",

请勿使用Runtime.getRuntime().maxMemory(),因为您很可能会比可用内存和OOM更频繁地使用更多内存,而是使用内存类并按以下方式计算缓存的大小:

Never use Runtime.getRuntime().maxMemory() as you will most likely use more memory than availabe and OOM more often, instead use the memory class and calculate the size of the cache as follows:

    /** 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)

这篇关于如何防止LRU缓存android中的内存不足错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆