原文网址:
1. http://xiaxveliang.blog.163.com/blog/static/297080342013827768676/
2. http://kylines.iteye.com/blog/1660180
1、权限:
1)联网权限
2)图片存储到sdcard的权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
2、根据给定URL,下载网络图片:
public Bitmap downloadPic(Context context, String pUrl) {
URL url = null;
HttpURLConnection conn = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
Bitmap bitmap = null;
String filePath = null;
try {
if (bitmap == null) {
url = new URL(pUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
byte[] pArray = baos.toByteArray();
bitmap = BitmapFactory
.decodeByteArray(pArray, 0, pArray.length);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
} catch (IOException e) {
e.printStackTrace();
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
} catch (OutOfMemoryError e) {
e.printStackTrace();
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
} catch (Exception e) {
e.printStackTrace();
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
} finally {
if (conn != null) {
conn.disconnect();
}
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bitmap;
}