安卓如何显示一张网络图片呢?其实很简单,不过新手可能会碰壁,为什么我明明按照网上的栗子写了,程序运行还是跳出错误呢?为什么?为什么?哈哈,我刚开始也纳闷,不过后来查阅了下资料,才知道原来这种获取网络资源的操作是很耗时的,需要进行异步操作。下面我们用AsycTask来进行异步操作。代码如下
new AsyncTask<String,Void,Void>()
{
@Override
protected Void doInBackground(String... params) {
try {
URL myurl=new URL(params[0 ]);
HttpURLConnection conn = null ;
try {
conn = (HttpURLConnection) myurl.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
conn.setDoInput(true );
try {
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
InputStream is = null ;
try {
is = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
bitmap = BitmapFactory.decodeStream (is);
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null ;
}
}.execute(url );//传入url
showimage .setImageBitmap(bitmap );//设置Imageview的Bitmap