如何从doinbackground()执行其他线程

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

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

我同意323go的意见

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

作为替代方案,您可以使用https://github.com/octo-online/robospice 。 你可以制作多个spice请求。

通用图像加载器

要下载和显示大量图像,请使用列表视图或网格视图。 为此,您可以使用Universal Image Loader或Lazy列表。 Universal Image loader作为惰性列表使用示例原则。

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

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

url被认为是关键。 图像缓存到SD卡或手机内存。 可以指定缓存的位置。 如果图像存在于缓存中。 显示来自缓存的图像,如果没有下载,缓存和显示图像。

两者都使用缓存。 Universal Image Loader有很多配置选项。 https://github.com/nostra13/Android-Universal-Image-Loader

查看链接中的function。

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

  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