我在我的 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/