//网络权限
<uses-permission android:name="android.permission.INTERNET" />
ImageView mImgView;
String url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201707%2F15%2F20170715164510_xm2yL.thumb.400_0.jpeg&refer=http%3A%2F%2Fb-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623550913&t=d8cae253f81749dbb3da16509d0b1abd" ;
//在消息队列中实现对控件的更改
private Handler handle = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
System.out.println("111");
Bitmap bmp=(Bitmap)msg.obj;
mImgView.setImageBitmap(bmp);
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cropImageView = (CropImageView) findViewById(R.id.cropImageView);
mImgView = (ImageView) findViewById(R.id.imgView);
//新建线程加载图片信息,发送到消息队列中
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Bitmap bmp = getURLimage(url);
Message msg = new Message();
msg.what = 0;
msg.obj = bmp;
System.out.println("000");
handle.sendMessage(msg);
}
}).start();
}
//加载图片
public Bitmap getURLimage(String url) {
Bitmap bmp = null;
try {
URL myurl = new URL(url);
// 获得连接
HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
conn.setConnectTimeout(6000);//设置超时
conn.setDoInput(true);
conn.setUseCaches(false);//不缓存
conn.connect();
InputStream is = conn.getInputStream();//获得图片的数据流
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return bmp;
}