Android:使用Asynctask从Web加载图像

Hub*_*ert 36 android android-asynctask

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

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

    }
Run Code Online (Sandbox Code Playgroud)

我想过这样的事情:

替换:

mChart.setImageBitmap(download_Image(graph_URL));
Run Code Online (Sandbox Code Playgroud)

通过类似的东西:

mChart.setImageBitmap(new DownloadImagesTask().execute(graph_URL));
Run Code Online (Sandbox Code Playgroud)

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


}
Run Code Online (Sandbox Code Playgroud)

但如何在onPostExecute(位图结果)中传递对mChart的引用??? 我是否需要以某种方式传递URL?我想替换所有代码行:

mChart1.setImageBitmap(download_Image(URL_1));
mChart2.setImageBitmap(download_Image(URL_2));
Run Code Online (Sandbox Code Playgroud)

与类似的东西...但在Asynctask方式!

mChart1.setImageBitmap(new DownloadImagesTask().execute(graph_URL_1));
mChart2.setImageBitmap(new DownloadImagesTask().execute(graph_URL_2));
Run Code Online (Sandbox Code Playgroud)

有一个简单的解决方案吗?我在这里弄错了吗?

Jan*_*usz 75

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

Picasso为您节省了下载,设置和缓存图像的所有问题.一个简单示例所需的整个代码是:

Picasso.with(context).load(url).into(imageView);
Run Code Online (Sandbox Code Playgroud)

如果你真的想自己动手,请使用下面的旧答案.


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

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

mChart.setTag(URL);
new DownloadImageTask.execute(mChart);
Run Code Online (Sandbox Code Playgroud)

Task类:

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) {
   ...
}
Run Code Online (Sandbox Code Playgroud)

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

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


小智 23

试试这段代码:

ImageView myFirstImage = (ImageView) findViewById(R.id.myFirstImage);
ImageView mySecondImage = (ImageView) findViewById(R.id.mySecondImage);
ImageView myThirdImage = (ImageView) findViewById(R.id.myThirdImage);

String URL1 = "http://www.google.com/logos/2013/estonia_independence_day_2013-1057005.3-hp.jpg";
String URL2 = "http://www.google.com/logos/2013/park_su-geuns_birthday-1055005-hp.jpg";
String URL3 = "http://www.google.com/logos/2013/anne_cath_vestlys_93rd_birthday-1035005-hp.jpg";


myFirstImage.setTag(URL1);
mySecondImage.setTag(URL2);
myThirdImage.setTag(URL3);


new DownloadImageTask.execute(myFirstImage);
new DownloadImageTask.execute(mySecondImage);
new DownloadImageTask.execute(myThirdImage);



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) {

        Bitmap bmp =null;
        try{
            URL ulrn = new URL(url);
            HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
            InputStream is = con.getInputStream();
            bmp = BitmapFactory.decodeStream(is);
            if (null != bmp)
                return bmp;

            }catch(Exception e){}
        return bmp;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • `return download_Image((String)imageView.getTag());`给出错误。“ getTag必须从UI线程中调用” (2认同)