首先创建一个Handler
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg){
switch(msg.what){
case 1:
imageView.setImageBitmap((Bitmap) msg.obj);
break;
}
}
};
然后异步加载网络图片
Thread thread = new Thread(){
public void run(){
try {
String path="http://n.sinaimg.cn/news/1_img/upload/8de453bf/20170301/f2KQ-fyawhqy3351967.jpg";
URL url=new URL(path);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(8000);
connection.connect();
if(connection.getResponseCode()==200){
InputStream inputStream=connection.getInputStream();
Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
Message msg=Message.obtain();
msg.obj=bitmap;
msg.what=1;
handler.sendMessage(msg);
}else{
Message msg=Message.obtain();
msg.what=2;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
break;