public void download(final Context context, final String url) {
new Thread(new Runnable() {
@Override
public void run() {
//下载图片
Bitmap bitmap = getImageFromNet(url);
// ivIcon.setImageBitmap(bitmap); // 设置imageView显示的图片
if (bitmap != null) {
Message msg = new Message();
msg.what = SUCCESS;
msg.obj = bitmap;
handler.sendMessage(msg);
System.out.println("下载成功");
Looper.prepare();
Toast.makeText(context, "下载成功", Toast.LENGTH_SHORT).show();
Looper.loop();
} else {
System.out.println("下载失败");
Looper.prepare();
Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}
}).start();
}
/**
* 根据url连接取网络抓去图片返回*
* @param url
* @return url对应的图片
*/
private Bitmap getImageFromNet(String url) {
HttpURLConnection conn = null;
try {
URL mURL = new URL(url); // 创建一个url对象
// 得到http的连接对象
conn = (HttpURLConnection) mURL.openConnection();
conn.setRequestMethod("GET"); // 设置请求方法为Get
conn.setConnectTimeout(10000); // 设置连接服务器的超时时间, 如果超过10秒钟, 没有连接成功, //
// 会抛异常
conn.setReadTimeout(10000); // 设置读取数据时超时时间, 如果超过5秒, 抛异常
conn.setDoInput(true);
conn.connect(); // 开始链接
int responseCode = conn.getResponseCode(); // 得到服务器的响应码
if (responseCode == 200) {
InputStream is = conn.getInputStream(); // 获得服务器返回的流数据
if (is != null)
Log.e(TAG, "is is not null" + is.toString());
/**
* 第一种方法去解析图片
*/
// 将流转换成字节
byte[] data = readStream(is);
if (data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);
return bitmap;
}
/**
* 第二种方法解析图片
*/
// Bitmap bitmap = BitmapFactory.decodeStream(is); // 根据 流数据
// return bitmap;
} else {
System.out.println(responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect(); // 断开连接
}
}
return null;
}
/**
* 得到图片字节流 数组大小
*
* @param inStream
* @return
* @throws Exception
*/
public byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}