gpt4 book ai didi

android - 在android的后台线程中从磁盘加载缓存图像

转载 作者:行者123 更新时间:2023-11-30 03:40:12 25 4
gpt4 key购买 nike

我有一个 ListView ,其中的图像是从 Internet 加载的,然后缓存在磁盘上。滚动时,我正在尝试使用 ExecutorService 在后台线程中从磁盘加载图像(因为滚动时会有多个图像)——像这样:

executorService.submit(new Runnable() {
@Override
public void run() {
// load images from the disk
// reconnect with UI thread using handler
}
}

但是,滚动一点也不流畅,而且非常不稳定 - 好像 UI 线程在某处被阻塞了。但是当我评论这个给定的代码时,滚动很流畅。我无法理解我的实现中的缺陷。

编辑:刚才我发现当我将消息从后台线程传递到 UI 线程时出现了问题。如果我评论那部分,滚动很流畅(但当然不显示图像)

最佳答案

您可以使用延迟加载或通用图像加载器

Lazy List 是使用 url 从 sdcard 或 fomr 服务器延迟加载图像。这就像按需加载图像。

图像可以缓存到本地 sd 卡或手机内存中。网址被认为是关键。如果 key 存在于 sdcard 中,则显示来自 sd 卡的图像,否则通过从服务器下载图像并将其缓存到您选择的位置来显示图像。缓存限制可以设置。您还可以选择自己的位置来缓存图像。也可以清除缓存。

而不是用户等待下载大图像,然后显示惰性列表按需加载图像。由于图像区域已缓存,您可以离线显示图像。

https://github.com/thest1/LazyList .惰性列表

在你的getview中

imageLoader.DisplayImage(imageurl, imageview); ImageLoader Display method

public void DisplayImage(String url, ImageView imageView) //url and imageview as parameters
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url); //get image from cache using url as key
if(bitmap!=null) //if image exists
imageView.setImageBitmap(bitmap); //dispaly iamge
else //downlaod image and dispaly. add to cache.
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}

Lazy List 的替代品是 Universal Image Loader

https://github.com/nostra13/Android-Universal-Image-Loader .

它基于 Lazy List(工作原理相同)。但它还有很多其他配置。我更愿意使用 Universal Image Loader,因为它为您提供了更多配置选项。如果下载失败,您可以显示错误图像。可以显示带圆角的图像。可以缓存在磁盘或内存上。可以压缩图片。

在您的自定义适配器构造函数中

 File cacheDir = StorageUtils.getOwnCacheDirectory(a, "your folder");

// Get singletone instance of ImageLoader
imageLoader = ImageLoader.getInstance();
// Create configuration for ImageLoader (all options are optional)
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a)
// You can pass your own memory cache implementation
.discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache implementation
.discCacheFileNameGenerator(new HashCodeFileNameGenerator())
.enableLogging()
.build();
// Initialize ImageLoader with created configuration. Do it once.
imageLoader.init(config);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_id)//display stub image
.cacheInMemory()
.cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(20))
.build();

在你的 getView() 中

ImageView image=(ImageView)vi.findViewById(R.id.imageview); 
imageLoader.displayImage(imageurl, image,options);//provide imageurl, imageview and options

您可以配置其他选项以满足您的需要。

与延迟加载/通用图像加载器一起,您可以view holder 以实现平滑滚动和性能

http://developer.android.com/training/improving-layouts/smooth-scrolling.html .

关于android - 在android的后台线程中从磁盘加载缓存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15876520/

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