Android:使用 Asynctask 从 Web 加载图像 [英] Android : Loading an image from the Web with Asynctask

查看:24
本文介绍了Android:使用 Asynctask 从 Web 加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用 Asynctask 替换以下代码行?你如何从 Asynctask 中取回"位图?谢谢.

How do I replace the following lines of code with an Asynctask ? How do you "get back" the Bitmap from the Asynctask ? Thank you.

ImageView mChart = (ImageView) findViewById(R.id.Chart);
String URL = "http://www...anything ...";

mChart.setImageBitmap(download_Image(URL));

public static Bitmap download_Image(String url) {

        //---------------------------------------------------
        Bitmap bm = null;
        try {
            URL aURL = new URL(url);
            URLConnection conn = aURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
        } catch (IOException e) {
            Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
        } 
        return bm;
        //---------------------------------------------------

    }

我想过这样的事情:

替换:

mChart.setImageBitmap(download_Image(graph_URL));

通过类似:

mChart.setImageBitmap(new DownloadImagesTask().execute(graph_URL));

public class DownloadImagesTask extends AsyncTask<String, Void, Bitmap> {

@Override
protected Bitmap doInBackground(String... urls) {
    return download_Image(urls[0]);
}

@Override
protected void onPostExecute(Bitmap result) {
    mChart.setImageBitmap(result);              // how do I pass a reference to mChart here ?
}


private Bitmap download_Image(String url) {
    //---------------------------------------------------
    Bitmap bm = null;
    try {
        URL aURL = new URL(url);
        URLConnection conn = aURL.openConnection();
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        bm = BitmapFactory.decodeStream(bis);
        bis.close();
        is.close();
    } catch (IOException e) {
        Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
    } 
    return bm;
    //---------------------------------------------------
}


}

但是如何在 onPostExecute(Bitmap result) 中传递对 mChart 的引用???我需要以某种方式通过 URL 传递它吗?我想替换我所有的代码行:

but How do I pass a reference to mChart in onPostExecute(Bitmap result) ??? Do I need to pass it with the URL in some way ? I would like to replace all my lines of code :

mChart1.setImageBitmap(download_Image(URL_1));
mChart2.setImageBitmap(download_Image(URL_2));

有类似的东西......但以异步任务的方式!

with something similar ... but in Asynctask way !

mChart1.setImageBitmap(new DownloadImagesTask().execute(graph_URL_1));
mChart2.setImageBitmap(new DownloadImagesTask().execute(graph_URL_2));

有没有简单的解决方案?我这里有什么问题吗?

Is there an easy solution for this ? Do I get something wrong here ?

推荐答案

如果没有充分的理由自己下载图像,那么我建议使用 毕加索.

If there is no good reason to download the image yourself then I would recommend to use Picasso.

Picasso 为您解决下载、设置和缓存图像的所有问题.一个简单示例所需的全部代码是:

Picasso saves you all the problems with downloading, setting and caching images. The whole code needed for a simple example is:

Picasso.with(context).load(url).into(imageView);

如果您真的想自己做所有事情,请使用我下面的旧答案.

If you really want to do everything yourself use my older answer below.

如果图像不是那么大,您可以只使用匿名类来执行异步任务.这会是这样的:

If the image is not that big you can just use an anonymous class for the async task. This would like this:

ImageView mChart = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...anything ...";

mChart.setTag(URL);
new DownloadImageTask.execute(mChart);

任务类:

public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {

ImageView imageView = null;

@Override
protected Bitmap doInBackground(ImageView... imageViews) {
    this.imageView = imageViews[0];
    return download_Image((String)imageView.getTag());
}

@Override
protected void onPostExecute(Bitmap result) {
    imageView.setImageBitmap(result);
}


private Bitmap download_Image(String url) {
   ...
}

在标签中隐藏 URL 有点棘手,但如果您有很多想要以这种方式填充的图像视图,它在调用类中看起来会更好.如果您在 ListView 中使用 ImageView 并且想知道 ImageView 在下载图像期间是否被回收,这也很有帮助.

Hiding the URL in the tag is a bit tricky but it looks nicer in the calling class if you have a lot of imageviews that you want to fill this way. It also helps if you are using the ImageView inside a ListView and you want to know if the ImageView was recycled during the download of the image.

我写过如果你的图片不是那么大,因为这将导致任务有一个指向底层活动的隐式指针,导致垃圾收集器将整个活动保存在内存中,直到任务完成.如果用户在位图下载时移动到应用程序的另一个屏幕,则无法释放内存,这可能会使您的应用程序和整个系统变慢.

I wrote if you Image is not that big because this will result in the task having a implicit pointer to the underlying activity causing the garbage collector to hold the whole activity in memory until the task is finished. If the user moves to another screen of your app while the bitmap is downloading the memory can't be freed and it may make your app and the whole system slower.

这篇关于Android:使用 Asynctask 从 Web 加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆