1, 使用HttpURLConnection 连接类进行下载。
2,ip, URL 是实现的必然点。
3,下载后保存的路径。
4,从网路上读数据写到本地中。
5,注意资源回收。
6,注意点:当你下载的内容比较小的时候可以不需要进行分块,但是当你下载的文件比较大的时候,若你的程式除了下载还需要做其他的事情那么请你住以后一些保护操作。比如下载过程中断网了的处理,网络连接超时的处理,同时注意IO占用的问题,如此才能是你的程式跑得更加的顺畅。
如果你是做一个定向的网路交互,即服务器和你的交互协议有特殊的信息需要交互,那么可以在HttpURLConnection上添加一些信息,或者根据两者协议进行握手既可以将架构设计得更复杂。
/**
* 下載google天氣圖標
*
* @param context
* @param ip
* @param iconURL
*/
private void downLoadGoogleIcon(Context context, String ip, String iconURL) {
HttpURLConnection httpConnection = null;
InputStream is = null;
FileOutputStream fos = null;
byte buf[] = null;
try {
String icon = null;
if (iconURL.indexOf(http) != -1) {
icon = iconURL;
} else {
if (ip.indexOf(http) != -1) {
icon = ip + iconURL;
} else {
icon = http + ip + iconURL;
}
}
if(icon == null){
throw new Exception("访问的URL不存在,请重试。");
}
URL url = new URL(icon);
Log.i(TAG, "download icon url = " + icon);
// 图标保存的路径
String path = Environment.getDataDirectory() + context.getString(R.string.googleIconPath);
httpConnection = (HttpURLConnection) url.openConnection();
is = httpConnection.getInputStream(); // 获取输入流
File pathFile = new File(path);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
fos = new FileOutputStream(new File(path + getFileNameFromUrl(iconURL)), true); // 获取输出流
buf = new byte[1024 * 4];
int len = 0;
while ((len = is.read(buf)) > 0) {
fos.write(buf, 0, len);
}
httpConnection.disconnect();
is.close();
fos.flush();
fos.close();
buf = null;
httpConnection = null;
is = null;
fos = null;
} catch (Exception e) {
Log.e(TAG, "Download Icon " + e.toString());
} finally { // 记得在此回收资源虽然 繁琐但是影响很大。
try {
if (is != null) {
is.close();
}
is = null;
if (fos != null) {
fos.close();
}
fos = null;
if (httpConnection != null) {
httpConnection.disconnect();
httpConnection = null;
}
if (buf != null) {
buf = null;
}
} catch (Exception e2) {
}
}
}
本实例下载的是小图标,消耗资源及cpu的占用都不是很高,所以相当简单。
希望对初次接触Android的道友有所帮助。