gpt4 book ai didi

android - LruCache 不工作

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:52:20 29 4
gpt4 key购买 nike

    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
};
URL url = new URL("http://s2.goodfon.ru/image/260463-1920x1200.jpg");
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) url.getContent(), null, options);
if(bitmap != null)
Log.i("Success", "BITMAP IS NOT NULL");

String key = "myKey";
Log.i("Get is null", "putting myKey");
mMemoryCache.put(key, bitmap);

Bitmap newBitmap = mMemoryCache.get(key);
if(newBitmap == null)
Log.i("newBitmap", "is null");

你好,这是一个代码。我成功地从 URL 获取位图(日志显示位图不为空,我可以轻松显示它)。然后我试图将它放入 LruCache 并取回它,但它返回 null。 (日志显示 newBitmap 为空)。我的错误在哪里?请告诉我。Android 4.1.2 缓存大小 8192 Kb。

最佳答案

如果它在磁盘上是 1.19 MB 但在内存中大约是 9 MB,这意味着作为一个压缩的 JPEG 文件,它是 1.19 MB,一旦你将它提取到一个可以显示的位图(未压缩)中,它将占用 9 MB 在内存中。如果它是代码 fragment 中 url 所建议的 1920 x 1200 像素图像,则该图像将占用 1920 x 1200 x 4 字节的内存(每个像素 4 个字节表示从 0 到 256 的 ARGB 值乘以 230 万总像素= 9,216,000 字节)。如果您将可用内存的 1/8 用于此缓存,则 9MB 可能/可能超过该总内存空间,因此位图永远不会进入缓存或立即被逐出。

如果图像太大(使用 BitmapFactory.Options.inSampleSize),您可能想要在解码时对图像进行下采样...如果您使用它,网络上有很多文档我们还不熟悉)。

此外,您还使用 Runtime.maxMemory 来计算缓存大小。这意味着您正在请求允许整个 VM 使用的最大内存量。

http://developer.android.com/reference/java/lang/Runtime.html#maxMemory%28%29

更常见的方法是使用 ActivityManager.getMemoryClass() 方法返回给您的值。

这里有一个示例代码 fragment 和文档中的方法定义以供引用。

    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
int memClassBytes = am.getMemoryClass() * 1024 * 1024;
int cacheSize = memClassBytes / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize)

http://developer.android.com/reference/android/app/ActivityManager.html#getMemoryClass%28%29

关于android - LruCache 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15459834/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com