在我的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;
}
}
如何为每个图像创建一个AsyncTask的新实例? – Merlevede
我刚告诉他/她在下面的答案中这样做! – Eenvincible