且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

安卓:从Web与AsyncTask的加载图像

更新时间:2023-08-19 18:36:10

如果没有充分的理由对自己下载的图像,然后我会建议使用的毕加索。

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

毕加索可以节省您所有的问题,下载,设置和缓存的图像。 需要一个简单的例子,整个code是:

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是有点棘手,但它会在调用的类更好,如果你有很多要填补这样imageviews的。它还帮助,如果你正在使用一个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.