解决安卓ImageView显示网络图片的问题
网上许多直接在主线程中获取图片,并进行更新,实测不可行,因为:
在子线程里只能进行网络请求的操作,但是子线程没有刷新ui的权限,
确实可以拿到图片,但是无法显示出来。
所以需要开启一个线程去获取网络资源,然后用handler更新UI。
//在方法中调用getimage()
// 刷新ui
private Handler handler = new Handler() {
public void handleMessage(Message message) {
Bitmap bitmap = (Bitmap) message.obj;
head_img.setImageBitmap(bitmap);
}
};
public void getimage(final String src) {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url=new URL(src);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input=connection.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(input);
input.close();
Message msg = handler.obtainMessage();
msg.obj = bmp;
handler.sendMessage(msg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
成功显示图片: