我想使用ImageLoader.loadImage
下载多个图像,这将启动多个线程。因为它们要花一些时间才能执行,而且我不想锁定UI,所以我想在AsyncTask的doInBackground()
函数中运行它们。
但是,我无法在doInBackground()
函数中启动新线程。有没有解决的办法?
最佳答案
我同意323go的评论
AsyncTask被设计为围绕Thread和Handler的帮助器类,并且不构成通用的线程框架。理想情况下,应将AsyncTasks用于较短的操作(最多几秒钟)。如果需要使线程长时间运行,则强烈建议您使用java.util.concurrent pacakge提供的各种API,例如执行程序,ThreadPoolExecutor和FutureTask。 (直接来自文档)
或者,您可以使用https://github.com/octo-online/robospice。您可以提出多个香料请求。
通用图像加载器
要下载并显示大量图像,请使用列表视图或网格视图。为此,您可以使用Universal Image Loader或惰性列表。通用图像加载器按照示例原则作为惰性列表工作。
我必须显示picasa相册公用文件夹中的图像(大约300-500)。我发出了一个http请求,响应为json。我使用asynctask发布http请求,获取响应,解析json以获取url。一旦获得url,就使用Universal Image Loader加载图像。因此,您可以将asynctask用于短期运行操作。
假设您可以一次查看一个列表中的3张图像。将下载三个图像,如果没有,则将其缓存并显示。滚动时,重复此过程。一旦缓存的图像就无需再次下载。在这种情况下,UI不会被阻止。您可以随时向下滚动。
网址被认为是关键。图像被缓存到sdcard或手机内存中。可以指定缓存的位置。如果图像存在于缓存中。从缓存中显示图像,如果不下载,则缓存并显示图像。
两者都使用缓存。 Universal Image Loader具有许多配置选项。
https://github.com/nostra13/Android-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
您可以配置其他选项以满足您的需求。
您应该使用一个观察器,以实现平滑的滚动和性能。 http://developer.android.com/training/improving-layouts/smooth-scrolling.html