简体   繁体   English

Android AsyncTask下载多个图像

[英]Android AsyncTask Download multiple Images

In my Android App, I have an AsyncTask to Download a Picture from the Web and Show it in the UI (in onPostExecute() I'm generating a new ImageView). 在我的Android应用中,我有一个AsyncTask可以从网上下载图片并在UI中显示(在onPostExecute()中,我正在生成一个新的ImageView)。 How can I make an AsyncTask which is downloading more than one Image at the same Time, and show the single Images directly when they are downloaded, even when the others aren't ready? 如何制作一个AsyncTask,它可以同时下载多个映像,并在下载单个映像时直接显示它们,即使其他映像还没有准备好呢?

This is my Code: 这是我的代码:

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;
        }

    }

Since you cannot make two requests at once, you can alternatively do the following: 由于您无法一次发出两个请求,因此您可以选择执行以下操作:

  • First, in your activity, create your AsyncTask instance and execute it with an argument like "firstImage" and then in doInBackground(), simply check to see if that is the value of the argument passed and if so, download the first image. 首先,在您的活动中,创建您的AsyncTask实例,并使用“ firstImage”之类的参数执行它,然后在doInBackground()中,只需检查以查看是否是传递的参数的值,如果是,则下载第一个图像。 After the image is downloaded, save it somewhere in a local variable or whatever you want. 下载图像后,将其保存在本地变量中或所需的任何位置。 Then return a string like "firstImage". 然后返回一个字符串,例如“ firstImage”。 Inside onPostExecute, just check the value of result and pass back the image to the activity which will update the UI. 在onPostExecute内,只需检查result的值,然后将图像传递回将更新UI的活动。
  • Secondly, once you have updated the UI with the first Image, make a second Async call with a string like "secondImage" and repeat the same process as before and update the UI - this will add the second image to the UI. 其次,一旦使用第一个图像更新了UI,请使用“ secondImage”之类的字符串进行第二个Async调用,并重复与以前相同的过程并更新UI-这会将第二个图像添加到UI。 You won't need a library for this! 您不需要为此的图书馆!

I recommend to you to use the Universal Image Loader library to download the images in android. 我建议您使用Universal Image Loader库在android中下载图像。

It download the image as well do some more good things like caching the images and manage the memory very tricky. 它也下载映像,并做一些更好的事情,例如缓存映像和管理内存非常棘手。

Update 更新资料

If you do not want to cache the images then you can disable this feature using the Configuration in the Universal Image Loader library. 如果您不想缓存图像,则可以使用Universal Image Loader库中的“ Configuration禁用此功能。

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

Just make use of onProgressUpdate(Progress...) . 只需使用onProgressUpdate(Progress...) Change your second generic type to Bitmap and call publishProgress() after you have finished loading an image. 完成加载图像后,将第二个通用类型更改为Bitmap并调用publishProgress()

我建议使用毕加索(Picasso skipMemoryCache()如果您根本不希望缓存图像,则可以在其中使用skipMemoryCache()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM