从URL下载图像

时间:2016-06-03 16:48:43

标签: android

我正在学习Android编程以及出了什么问题?

ImageView im = (ImageView) findViewById(R.id.imageView);
try {
     URL  u = new URL("http");
     HttpURLConnection ur = (HttpURLConnection) u.openConnection();
     InputStream in = ur.getInputStream();
     Bitmap bs = BitmapFactory.decodeStream(in);

     im.setImageBitmap(bs);

     in.close();
} catch (Exception e) {
     e.printStackTrace();
}

2 个答案:

答案 0 :(得分:0)

你不能在主线程上运行,只需使用新线程:

Thread thread = new Thread(new Runnable()
{
    @Override
    public void run() 
    {
        try 
        {
            //Your code goes here
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
});

thread.start(); 

答案 1 :(得分:0)

您是否搜索了Picasso library

使用picasso,您可以在View上绑定图像请求的位图(即ImageView)。与它的工作方式无关。

Picasso.with(context)
        .load(imageUri)
        .into(viewToAttach);

您可以使用回调来捕获超时或错误响应等错误。

相关问题