如何使用AsyncTask下载和显示位图

时间:2011-04-04 17:18:49

标签: android memory download bitmap android-asynctask

我是android的新手,过去几天我找不到问题原因:

我有一个带有ListView的ActivityA。单击ListView中的每个项目都将打开ActivityB, 这将显示在ImageView中从网络下载的一些图像。 因此,在ActivityB中,我有一个包含以下代码的循环来尝试下载图像:

ImageView ivPictureSmall = new ImageView(this);
ImageDownloader ido = new ImageDownloader();
ido.download(this.getResources().getString(R.string.images_uri) + strPictureSmall, ivPictureSmall);
ivPictureSmall.setPadding(3, 5, 3, 5);
linearLayout.addView(ivPictureSmall);

类ImageDownloader


public class ImageDownloader
{
    public void download(String url, ImageView imageView)
    {
            BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
            task.execute(url);
    }
}

类BitmapDownloaderTask


class BitmapDownloaderTask extends AsyncTask
{
    private String url;
    private final WeakReference imageViewReference;

    public BitmapDownloaderTask(ImageView imageView)
    {
        imageViewReference = new WeakReference(imageView);
    }

    @Override
    // Actual download method, run in the task thread
    protected Bitmap doInBackground(String... params)
    {
        // params comes from the execute() call: params[0] is the url.
        return downloadBitmap(params[0]);
    }

    @Override
    // Once the image is downloaded, associates it to the imageView
    protected void onPostExecute(Bitmap bitmap)
    {
        if (isCancelled())
        {
            bitmap = null;
        }

        if (imageViewReference != null)
        {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }

    }

    protected Bitmap downloadBitmap(String url)
    {
        final DefaultHttpClient client = new DefaultHttpClient();
        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(new FlushedInputStream(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: " + e.toString());
        } finally {
            if (client != null) {
                //client.close();

            }
        }
        return null;
    }


    static class FlushedInputStream extends FilterInputStream
    {
        public FlushedInputStream(InputStream inputStream)
        {
            super(inputStream);
        }

        @Override
        public long skip(long n) throws IOException
        {
            long totalBytesSkipped = 0L;
            while (totalBytesSkipped 

When I clicked an item in the ListView in ActivityA, It correctly goes to ActivityB, and ActivityB shows the images. When I press the "Back" button on ActivityB to back up to ActivityA, then click again on an item in the ListView, I come to ActivityB and then I see am informed that the process closed unexpectedly.

When I attempt to debug, I noticed that the problem is in the linE:

final Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));

Which is in a protected Bitmap downloadBitmap(String url) function.

I read about a bug in Android with BitmapFactory.decodeStream so I added FlushedInputStream to prevent it.

However, it seems to me this is not cause of the problem, since it was working when I first loaded ActivityB, but not the second time. Maybe I have a memory leak? (The pictures are big, and memory are not reycled after backing to ActivityA.)

If so, how can I clean up the associated memory? Or is the problem in something else?

ActivityA,但遇到了同样的问题。

1 个答案:

答案 0 :(得分:0)

您应该使用像PicassoVolley这样的图片加载库为您完成艰苦的工作。