//获取控件和设置成功和失败的信息码 private ImageView mViewById; private final int SUCCESS = 0; private final int FAIL = 1;
//传入路径并且获取bitmap对象,不为空传入handler处理 final String url ="http://10.000.241.00:8888/static/images/emp_photo/F000/F0000.JPG"; new Thread(new Runnable() { @Override public void run() { Bitmap bitmap = getImageFromNet(url); if (bitmap != null) { Message msg = new Message(); msg.what = SUCCESS; msg.obj = bitmap; handler.sendMessage(msg); } else { Message msg = new Message(); msg.what = FAIL; handler.sendMessage(msg); } } }).start();
//核心请求网络图片的方法 private Bitmap getImageFromNet(String url) { HttpURLConnection conn = null; try { URL mURL = new URL(url); conn = (HttpURLConnection) mURL.openConnection(); conn.setRequestMethod("GET"); //设置请求方法 conn.setConnectTimeout(10000); //设置连接服务器超时时间 conn.setReadTimeout(5000); //设置读取数据超时时间 conn.connect(); //开始连接 int responseCode = conn.getResponseCode(); //得到服务器的响应码 if (responseCode == 200) { //访问成功 InputStream is = conn.getInputStream(); //获得服务器返回的流数据 Bitmap bitmap = BitmapFactory.decodeStream(is); //根据流数据 创建一个bitmap对象 return bitmap; } else { //访问失败 Log.d("lyf--", "访问失败===responseCode:" + responseCode); } } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); //断开连接 } } return null; }
//开一个处理设置图片的handler private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case SUCCESS: Bitmap bitmap = (Bitmap) msg.obj; mViewById.setImageBitmap(bitmap); //设置imageView显示的图片 break; case FAIL: Toast.makeText(MainActivity.this, "图片加载失败", Toast.LENGTH_LONG).show(); break; } } };