2014-02-15 71 views
1

在我的Android应用程序中,我有一个AsyncTask从Web下载图片并在用户界面中显示它(在onPostExecute()我生成一个新的ImageView)。 如何使一个AsyncTask同时下载多个图像,并在下载时直接显示单个图像,即使其他图像尚未准备好?Android AsyncTask下载多个图像

这是我的代码:

public class DownloadImages extends 
      AsyncTask<Void, Void, Bitmap> { 


     @Override 
     protected Bitmap doInBackground(Void... params) { 

      Bitmap bitmap = null; 
      bitmap = downloadBitmap("HERE's MY URL"); 


      return bitmap; 
     } 

     @Override 
     protected void onPostExecute(Bitmap result) { 


      ImageView image = new ImageView(context); 
      image.setImageBitmap(result); 


      ((ViewGroup) planLinearLayout).addView(image); 


     } 


     } 

     public Bitmap downloadBitmap(String url) { 
      final AndroidHttpClient client = AndroidHttpClient 
        .newInstance("Android"); 
      final HttpGet getRequest = new HttpGet(url); 

      try { 
       HttpResponse response = client.execute(getRequest); 
       final int statusCode = response.getStatusLine().getStatusCode(); 
       if (statusCode != HttpStatus.SC_OK) { 
        Log.w("ImageDownloader", "Error " + statusCode 
          + " while retrieving bitmap from " + url); 
        return null; 
       } 

       final HttpEntity entity = response.getEntity(); 
       if (entity != null) { 
        InputStream inputStream = null; 
        try { 
         inputStream = entity.getContent(); 
         final Bitmap bitmap = BitmapFactory 
           .decodeStream(inputStream); 


         return bitmap; 
        } finally { 
         if (inputStream != null) { 
          inputStream.close(); 
         } 
         entity.consumeContent(); 
        } 
       } 
      } catch (Exception e) { 
       // Could provide a more explicit error message for IOException 
       // or 
       // IllegalStateException 
       getRequest.abort(); 
       Log.w("ImageDownloader", "Error while retrieving bitmap from " 
         + url); 
      } finally { 
       if (client != null) { 
        client.close(); 
       } 
      } 
      return null; 
     } 

    } 
+0

如何为每个图像创建一个AsyncTask的新实例? – Merlevede

+0

我刚告诉他/她在下面的答案中这样做! – Eenvincible

回答

1

我建议你使用通用图像装载机库下载图像的机器人。

它下载图像以及做一些更好的事情,如缓存图像和管理内存非常棘手。

更新

如果你不想缓存图像,那么你可以使用在通用图像装载机库Configuration禁用此功能。

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

+0

这就是我的问题:我不需要缓存图像,因为我从服务器加载图像,并且文件名相同,但图像每天都会更改(这是一个替代计划)。图书馆通过名称缓存图像,并始终显示相同的内容。 – jwandscheer

+0

UIL中没有禁用缓存的API吗? – Niko

+0

我已经更新了我的答案 –

1

我会推荐毕加索,在那里你可以使用skipMemoryCache(),如果你不希望图像被缓存的话。

2

既然你不能在一次两个请求,则可以选择执行以下操作:

  • 首先,在您的活动,创建您的AsyncTask实例,并包含“firstImage”的参数执行它,然后在doInBackground (),只需检查是否是通过参数的值,如果是,请下载第一个图像。下载图像后,将其保存在本地变量或任何你想要的地方。然后返回一个字符串,如“firstImage”。在onPostExecute中,只需检查结果的值并将图像传回给将更新UI的活动。其次,一旦你用第一个图像更新了UI,使用像“secondImage”这样的字符串进行第二次Async调用,并重复与之前相同的过程并更新UI - 这会将第二个图像添加到UI。你不需要一个图书馆!