gpt4 book ai didi

android - 从应用程序缓存加载时 ListView 滞后

转载 作者:行者123 更新时间:2023-11-29 14:15:59 25 4
gpt4 key购买 nike

我写了一小段代码,从互联网上下载图像并将它们缓存到缓存目录中。它在辅助线程中运行。

{

String hash = md5(urlString);
File f = new File(m_cacheDir, hash);

if (f.exists())
{
Drawable d = Drawable.createFromPath(f.getAbsolutePath());
return d;
}

try {
InputStream is = download(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");

if (drawable != null)
{
FileOutputStream out = new FileOutputStream(f);
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
bitmap.compress(CompressFormat.JPEG, 90, out);
}

return drawable;
} catch (Throwable e) { }

return null;
}

我使用这段代码在 ListView 项目中加载图片,它工作正常。如果我删除第一个 if (我从磁盘加载图像的地方)它运行顺利(并且每次都下载图片!)。如果我保留它,当你滚动 ListView 时,你会感觉到从磁盘加载图片时有些滞后,为什么?

最佳答案

为了回答“为什么”这个问题,我在我的 logcat 中遇到了很多 gc() 消息。 Android 在从磁盘解码文件之前分配内存,这可能导致垃圾收集,这对所有线程的性能都是痛苦的。当您对 jpeg 进行编码时,可能也会发生同样的情况。

对于解码部分,如果您有一个让 Android 就地解码图像的位图,您可以尝试重用现有位图。请查看以下代码 fragment :

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
options.inJustDecodeBounds = false;
options.inMutable = true;
if (oldBitmap != null) {
options.inBitmap = oldBitmap;
}
return BitmapFactory.decodeFile(f.getAbsolutePath(), options);

关于android - 从应用程序缓存加载时 ListView 滞后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12687757/

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