我在我的 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)