0

我想下载多个图像,使用ImageLoader.loadImage它们将启动多个线程。因为它们需要一段时间才能执行,而且我不想锁定 UI,所以我想在doInBackground()AsyncTask 的函数中运行它们。

但是我无法在doInBackground()函数中启动新线程。有没有解决的办法?

4

1 回答 1

1

我同意323go的评论

AsyncTask 被设计为围绕 Thread 和 Handler 的辅助类,并不构成通用线程框架。AsyncTasks 最好用于短时间的操作(最多几秒钟)。如果您需要保持线程长时间运行,强烈建议您使用 java.util.concurrent 包提供的各种 API,例如Executor、ThreadPoolExecutor 和 FutureTask。(直接来自文档)

作为替代方案,您可以使用https://github.com/octo-online/robospice。您可以提出多个香料请求。

通用图像加载器

要下载和显示大量图像,请使用列表视图或网格视图。为此,您可以使用 Universal Image Loader 或 Lazy list。通用图像加载器以惰性列表的示例原理工作。

我必须显示来自 picasa 相册公用文件夹的图像(大约 300 - 500)。我发出了一个http请求,响应是json。我使用 asynctask 发布 http 请求、获取响应、解析 json 以获取 url。获得网址后,我使用 Universal Image Loader 加载图像。因此,您可以使用 asynctask 进行短期运行操作。

假设您可以在列表中一次查看 3 张图像。这三个图像被下载,如果没有则被缓存并显示。当您滚动过程重复。一旦缓存的图像不需要再次下载。在这种情况下,UI 不会被阻止。您可以随时向下滚动。

Url 被认为是关键。图像缓存到 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

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

您应该使用 viewholder 来实现平滑的滚动和性能。http://developer.android.com/training/improving-layouts/smooth-scrolling.html

于 2013-04-01T18:46:42.767 回答