---
title: "<转载>andriod 断点续传和下载原理分析"
author: "hecal"
date: "2011-12-21T21:48:02Z"
tags: []
categories: ["移动开发"]
slug: "andriod"
draft: false
lastmod: "2011-12-27T14:07:35Z"
id: 1320069
url: "https://hecal.iteye.com/blog/1320069"
---

最近做一个文件上传和下载的应用对文件上传和下载进行了一个完整的流程分析  
以来是方便自己对文件上传和下载的理解，而来便于团队内部的分享  
故而做了几张图，将整体的流程都画下来，便于大家的理解和分析，如果有不完善的地方希望  
大家多提意见，  
由于参考了网上许多的资料，特此感谢

首先是文件上传，这个要用到服务器

![333.jpg](http://www.apkbus.com/data/attachment/forum/201112/20/1848519wkk73w2v0w007kx.jpg "333.jpg")

7 天前 上传

[**下载附件** (40.37 KB)](http://www.apkbus.com/plugin.php?id=modads%3Aad&aid=MTM4MDN8ZGJjYzQ0MmZ8MTMyNDk1NTgzOHwwfDE4OTY0&nothumb=yes "333.jpg 下载次数:1")

关键代码：

FileServer.java

Java代码

001. import java.io.File;
002. import java.io.FileInputStream;
003. import java.io.FileOutputStream;
004. import java.io.IOException;
005. import java.io.InputStream;
006. import java.io.OutputStream;
007. import java.io.PushbackInputStream;
008. import java.io.RandomAccessFile;
009. import java.net.ServerSocket;
010. import java.net.Socket;
011. import java.text.SimpleDateFormat;
012. import java.util.Date;
013. import java.util.HashMap;
014. import java.util.Map;
015. import java.util.Properties;
016. import java.util.Set;
017. import java.util.concurrent.ExecutorService;
018. import java.util.concurrent.Executors;
019. import util.FileLogInfo;
020. import util.StreamTool;
021. public class FileServer {
022. private ExecutorService executorService;//线程池
023. private int port;//监听端口
024. private boolean quit = false;//退出
025. private ServerSocket server;
026. private Map&lt;Long, FileLogInfo&gt; datas = new HashMap&lt;Long, FileLogInfo&gt;();//存放断点数据,以后改为数据库存放
027. public FileServer(int port)
028. {
029. this.port = port;
030. //创建线程池，池中具有(cpu个数\*50)条线程
031. executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 50);
032. }
033. /\**
034. \* 退出
035. \*/
036. public void quit()
037. {
038. this.quit = true;
039. try
040. {
041. server.close();
042. }catch (IOException e)
043. {
044. e.printStackTrace();
045. }
046. }
047. /\**
048. \* 启动服务
049. \* @throws Exception
050. \*/
051. public void start() throws Exception
052. {
053. server = new ServerSocket(port);//实现端口监听
054. while(!quit)
055. {
056. try
057. {
058. Socket socket = server.accept();
059. executorService.execute(new SocketTask(socket));//为支持多用户并发访问，采用线程池管理每一个用户的连接请求
060. }catch (Exception e)
061. {
062. e.printStackTrace();
063. }
064. }
065. }
066. private final class SocketTask implements Runnable
067. {
068. private Socket socket = null;
069. public SocketTask(Socket socket)
070. {
071. this.socket = socket;
072. }
073. @Override
074. public void run()
075. {
076. try
077. {
078. System.out.println("FileServer accepted connection "+ socket.getInetAddress()+ ":"+ socket.getPort());
079. //得到客户端发来的第一行协议数据：Content-Length=143253434;filename=xxx.3gp;sourceid=
080. //如果用户初次上传文件，sourceid的值为空。
081. InputStream inStream = socket.getInputStream();
082. String head = StreamTool.readLine(inStream);
083. System.out.println("FileServer head:"+head);
084. if(head!=null)
085. {
086. //下面从协议数据中提取各项参数值
087. String\[] items = head.split(";");
088. String filelength = items\[0].substring(items\[0].indexOf("=")+1);
089. String filename = items\[1].substring(items\[1].indexOf("=")+1);
090. String sourceid = items\[2].substring(items\[2].indexOf("=")+1);
091. //生成资源id，如果需要唯一性，可以采用UUID
092. long id = System.currentTimeMillis();
093. FileLogInfo log = null;
094. if(sourceid!=null && !"".equals(sourceid))
095. {
096. id = Long.valueOf(sourceid);
097. //查找上传的文件是否存在上传记录
098. log = find(id);
099. }
100. File file = null;
101. int position = 0;
102. //如果上传的文件不存在上传记录,为文件添加跟踪记录
103. if(log==null)
104. {
105. //设置存放的位置与当前应用的位置有关
106. File dir = new File("c:/temp/");
107. if(!dir.exists()) dir.mkdirs();
108. file = new File(dir, filename);
109. //如果上传的文件发生重名，然后进行改名
110. if(file.exists())
111. {
112. filename = filename.substring(0, filename.indexOf(".")-1)+ dir.listFiles().length+ filename.substring(filename.indexOf("."));
113. file = new File(dir, filename);
114. }
115. save(id, file);
116. }
117. // 如果上传的文件存在上传记录,读取上次的断点位置
118. else
119. {
120. System.out.println("FileServer have exits log not null");
121. //从上传记录中得到文件的路径
122. file = new File(log.getPath());
123. if(file.exists())
124. {
125. File logFile = new File(file.getParentFile(), file.getName()+".log");
126. if(logFile.exists())
127. {
128. Properties properties = new Properties();
129. properties.load(new FileInputStream(logFile));
130. //读取断点位置
131. position = Integer.valueOf(properties.getProperty("length"));
132. }
133. }
134. }
135. //\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*上面是对协议头的处理，下面正式接收数据\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\**
136. //向客户端请求传输数据
137. OutputStream outStream = socket.getOutputStream();
138. String response = "sourceid="+ id+ ";position="+ position+ "%";
139. //服务器收到客户端的请求信息后，给客户端返回响应信息：sourceid=1274773833264;position=position
140. //sourceid由服务生成，唯一标识上传的文件，position指示客户端从文件的什么位置开始上传
141. outStream.write(response.getBytes());
142. RandomAccessFile fileOutStream = new RandomAccessFile(file, "rwd");
143. //设置文件长度
144. if(position==0) fileOutStream.setLength(Integer.valueOf(filelength));
145. //移动文件指定的位置开始写入数据
146. fileOutStream.seek(position);
147. byte\[] buffer = new byte\[1024];
148. int len = -1;
149. int length = position;
150. //从输入流中读取数据写入到文件中，并将已经传入的文件长度写入配置文件，实时记录文件的最后保存位置
151. while( (len=inStream.read(buffer)) != -1)
152. {
153. fileOutStream.write(buffer, 0, len);
154. length += len;
155. Properties properties = new Properties();
156. properties.put("length", String.valueOf(length));
157. FileOutputStream logFile = new FileOutputStream(new File(file.getParentFile(), file.getName()+".log"));
158. //实时记录文件的最后保存位置
159. properties.store(logFile, null);
160. logFile.close();
161. }
162. //如果长传长度等于实际长度则表示长传成功
163. if(length==fileOutStream.length()){
164. delete(id);
165. }
166. fileOutStream.close();
167. inStream.close();
168. outStream.close();
169. file = null;
170. }
171. }
172. catch (Exception e)
173. {
174. e.printStackTrace();
175. }
176. finally{
177. try
178. {
179. if(socket!=null && !socket.isClosed()) socket.close();
180. }
181. catch (IOException e)
182. {
183. e.printStackTrace();
184. }
185. }
186. }
187. }
188. /\**
189. \* 查找在记录中是否有sourceid的文件
190. \* @param sourceid
191. \* @return
192. \*/
193. public FileLogInfo find(Long sourceid)
194. {
195. return datas.get(sourceid);
196. }
197. /\**
198. \* 保存上传记录，日后可以改成通过数据库存放
199. \* @param id
200. \* @param saveFile
201. \*/
202. public void save(Long id, File saveFile)
203. {
204. System.out.println("save logfile "+id);
205. datas.put(id, new FileLogInfo(id, saveFile.getAbsolutePath()));
206. }
207. /\**
208. \* 当文件上传完毕，删除记录
209. \* @param sourceid
210. \*/
211. public void delete(long sourceid)
212. {
213. System.out.println("delete logfile "+sourceid);
214. if(datas.containsKey(sourceid)) datas.remove(sourceid);
215. }
216. }

*复制代码*

由于在上面的流程图中已经进行了详细的分析，我在这儿就不讲了，只是在存储数据的时候服务器没有用数据库去存储，这儿只是为了方便，所以要想测试断点上传，服务器是不能停的，否则数据就没有了，在以后改进的时候应该用数据库去存储数据。  
文件上传客户端：

![222.jpg](http://www.apkbus.com/data/attachment/forum/201112/20/184848pajfr1zj2aagz4zg.jpg "222.jpg")

7 天前 上传

[**下载附件** (38.92 KB)](http://www.apkbus.com/plugin.php?id=modads%3Aad&aid=MTM3OTl8NzIyMzgwZmF8MTMyNDk1NTgzOHwwfDE4OTY0&nothumb=yes "222.jpg 下载次数:0")

关键代码：  
UploadActivity.java

Java代码

001. package com.hao;
002. import java.io.File;
003. import java.util.List;
004. import com.hao.upload.UploadThread;
005. import com.hao.upload.UploadThread.UploadProgressListener;
006. import com.hao.util.ConstantValues;
007. import com.hao.util.FileBrowserActivity;
008. import [android](http://www.apkbus.com/).app.Activity;
009. import android.app.Dialog;
010. import android.app.ProgressDialog;
011. import android.content.DialogInterface;
012. import android.content.Intent;
013. import android.content.res.Resources;
014. import android.net.Uri;
015. import android.os.Bundle;
016. import android.os.Environment;
017. import android.os.Handler;
018. import android.os.Message;
019. import android.util.Log;
020. import android.view.View;
021. import android.view.View.OnClickListener;
022. import android.widget.Button;
023. import android.widget.TextView;
024. import android.widget.Toast;
025. /\**
026. \*
027. \* @author Administrator
028. \*
029. \*/
030. public class UploadActivity extends Activity implements OnClickListener{
031. private static final String TAG = "SiteFileFetchActivity";
032. private Button download, upload, select\_file;
033. private TextView info;
034. private static final int PROGRESS\_DIALOG = 0;
035. private ProgressDialog progressDialog;
036. private UploadThread uploadThread;
037. private String uploadFilePath = null;
038. private String fileName;
039. /\** Called when the activity is first created. \*/
040. @Override
041. public void onCreate(Bundle savedInstanceState) {
042. super.onCreate(savedInstanceState);
043. setContentView(R.layout.upload);
044. initView();
045. }
046. private void initView(){
047. download = (Button) findViewById(R.id.download);
048. download.setOnClickListener(this);
049. upload = (Button) findViewById(R.id.upload);
050. upload.setOnClickListener(this);
051. info = (TextView) findViewById(R.id.info);
052. select\_file = (Button) findViewById(R.id.select\_file);
053. select\_file.setOnClickListener(this);
054. }
055. @Override
056. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
057. // TODO Auto-generated method stub
058. super.onActivityResult(requestCode, resultCode, data);
059. if (resultCode == RESULT\_OK) {
060. if (requestCode == 1) {
061. Uri uri = data.getData();    // 接收用户所选文件的路径
062. info.setText("select: " + uri); // 在界面上显示路径
063. uploadFilePath = uri.getPath();
064. int last = uploadFilePath.lastIndexOf("/");
065. uploadFilePath = uri.getPath().substring(0, last+1);
066. fileName = uri.getLastPathSegment();
067. }
068. }
069. }
070. protected Dialog onCreateDialog(int id) {
071. switch(id) {
072. case PROGRESS\_DIALOG:
073. progressDialog = new ProgressDialog(UploadActivity.this);
074. progressDialog.setProgressStyle(ProgressDialog.STYLE\_HORIZONTAL);
075. progressDialog.setButton("暂停", new DialogInterface.OnClickListener() {
076. @Override
077. public void onClick(DialogInterface dialog, int which) {
078. // TODO Auto-generated method stub
079. uploadThread.closeLink();
080. dialog.dismiss();
081. }
082. });
083. progressDialog.setMessage("正在上传...");
084. progressDialog.setMax(100);
085. return progressDialog;
086. default:
087. return null;
088. }
089. }
090. /\**
091. \* 使用Handler给创建他的线程发送消息，
092. \* 匿名内部类
093. \*/
094. private Handler handler = new Handler()
095. {
096. @Override
097. public void handleMessage(Message msg)
098. {
099. //获得上传长度的进度
100. int length = msg.getData().getInt("size");
101. progressDialog.setProgress(length);
102. if(progressDialog.getProgress()==progressDialog.getMax())//上传成功
103. {
104. progressDialog.dismiss();
105. Toast.makeText(UploadActivity.this, getResources().getString(R.string.upload\_over), 1).show();
106. }
107. }
108. };
109. @Override
110. public void onClick(View v) {
111. // TODO Auto-generated method stub
112. Resources r = getResources();
113. switch(v.getId()){
114. case R.id.select\_file:
115. Intent intent = new Intent();
116. //设置起始目录和查找的类型
117. intent.setDataAndType(Uri.fromFile(new File("/sdcard")), "\*/\*");//"\*/\*"表示所有类型，设置起始文件夹和文件类型
118. intent.setClass(UploadActivity.this, FileBrowserActivity.class);
119. startActivityForResult(intent, 1);
120. break;
121. case R.id.download:
122. startActivity(new Intent(UploadActivity.this, SmartDownloadActivity.class));
123. break;
124. case R.id.upload:
125. if(Environment.getExternalStorageState().equals(Environment.MEDIA\_MOUNTED))//判断SDCard是否存在
126. {
127. if(uploadFilePath == null){
128. Toast.makeText(UploadActivity.this, "还没设置上传文件", 1).show();
129. }
130. System.out.println("uploadFilePath:"+uploadFilePath+" "+fileName);
131. //取得SDCard的目录
132. File uploadFile = new File(new File(uploadFilePath), fileName);
133. Log.i(TAG, "filePath:"+uploadFile.toString());
134. if(uploadFile.exists())
135. {
136. showDialog(PROGRESS\_DIALOG);
137. info.setText(uploadFile+" "+ConstantValues.HOST+":"+ConstantValues.PORT);
138. progressDialog.setMax((int) uploadFile.length());//设置长传文件的最大刻度
139. uploadThread = new UploadThread(UploadActivity.this, uploadFile, ConstantValues.HOST, ConstantValues.PORT);
140. uploadThread.setListener(new UploadProgressListener() {
141. @Override
142. public void onUploadSize(int size) {
143. // TODO Auto-generated method stub
144. Message msg = new Message();
145. msg.getData().putInt("size", size);
146. handler.sendMessage(msg);
147. }
148. });
149. uploadThread.start();
150. }
151. else
152. {
153. Toast.makeText(UploadActivity.this, "文件不存在", 1).show();
154. }
155. }
156. else
157. {
158. Toast.makeText(UploadActivity.this, "SDCard不存在！", 1).show();
159. }
160. break;
161. }
162. }
163. }

*复制代码*

UploadThread.java

Java代码

01. package com.hao.upload;
02. import java.io.File;
03. import java.io.IOException;
04. import java.io.InputStream;
05. import java.io.OutputStream;
06. import java.io.RandomAccessFile;
07. import java.net.Socket;
08. import android.content.Context;
09. import android.util.Log;
10. import com.hao.db.UploadLogService;
11. import com.hao.util.StreamTool;
12. public class UploadThread extends Thread {
13. private static final String TAG = "UploadThread";
14. /\*需要上传文件的路径\*/
15. private File uploadFile;
16. /\*上传文件服务器的IP地址\*/
17. private String dstName;
18. /\*上传服务器端口号\*/
19. private int dstPort;
20. /\*上传socket链接\*/
21. private Socket socket;
22. /\*存储上传的数据库\*/
23. private UploadLogService logService;
24. private UploadProgressListener listener;
25. public UploadThread(Context context, File uploadFile, final String dstName,final int dstPort){
26. this.uploadFile = uploadFile;
27. this.dstName = dstName;
28. this.dstPort = dstPort;
29. logService = new UploadLogService(context);
30. }
31. public void setListener(UploadProgressListener listener) {
32. this.listener = listener;
33. }
34. /\**
35. \* 模拟断开连接
36. \*/
37. public void closeLink(){
38. try{
39. if(socket != null) socket.close();
40. }catch(IOException e){
41. e.printStackTrace();
42. Log.e(TAG, "close socket fail");
43. }
44. }
45. @Override
46. public void run() {
47. // TODO Auto-generated method stub
48. try {
49. // 判断文件是否已有上传记录
50. String souceid = logService.getBindId(uploadFile);
51. // 构造拼接协议
52. String head = "Content-Length=" + uploadFile.length()
53. \+ ";filename=" + uploadFile.getName() + ";sourceid="
54. \+ (souceid == null ? "" : souceid) + "%";
55. // 通过Socket取得输出流
56. socket = new Socket(dstName, dstPort);
57. OutputStream outStream = socket.getOutputStream();
58. outStream.write(head.getBytes());
59. Log.i(TAG, "write to outStream");
60. InputStream inStream = socket.getInputStream();
61. // 获取到字符流的id与位置
62. String response = StreamTool.readLine(inStream);
63. Log.i(TAG, "response:" + response);
64. String\[] items = response.split(";");
65. String responseid = items\[0].substring(items\[0].indexOf("=") + 1);
66. String position = items\[1].substring(items\[1].indexOf("=") + 1);
67. // 代表原来没有上传过此文件，往数据库添加一条绑定记录
68. if (souceid == null) {
69. logService.save(responseid, uploadFile);
70. }
71. RandomAccessFile fileOutStream = new RandomAccessFile(uploadFile, "r");
72. // 查找上次传送的最终位置，并从这开始传送
73. fileOutStream.seek(Integer.valueOf(position));
74. byte\[] buffer = new byte\[1024];
75. int len = -1;
76. // 初始化上传的数据长度
77. int length = Integer.valueOf(position);
78. while ((len = fileOutStream.read(buffer)) != -1) {
79. outStream.write(buffer, 0, len);
80. // 设置长传数据长度
81. length += len;
82. listener.onUploadSize(length);
83. }
84. fileOutStream.close();
85. outStream.close();
86. inStream.close();
87. socket.close();
88. // 判断上传完则删除数据
89. if (length == uploadFile.length())
90. logService.delete(uploadFile);
91. } catch (Exception e) {
92. e.printStackTrace();
93. }
94. }
95. public interface UploadProgressListener{
96. void onUploadSize(int size);
97. }
98. }

*复制代码*

下面是多线程下载

![111.jpg](http://www.apkbus.com/data/attachment/forum/201112/20/184944rgf88r1201kb7cgv.jpg "111.jpg")

7 天前 上传

[**下载附件** (34.38 KB)](http://www.apkbus.com/plugin.php?id=modads%3Aad&aid=MTM4MDV8ZmRjOTEwODl8MTMyNDk1NTgzOHwwfDE4OTY0&nothumb=yes "111.jpg 下载次数:0")

SmartDownloadActivity.java

Java代码

001. package com.hao;
002. import java.io.File;
003. import com.hao.R;
004. import com.hao.R.id;
005. import com.hao.R.layout;
006. import com.hao.download.SmartFileDownloader;
007. import com.hao.download.SmartFileDownloader.SmartDownloadProgressListener;
008. import com.hao.util.ConstantValues;
009. import android.app.Activity;
010. import android.os.Bundle;
011. import android.os.Environment;
012. import android.os.Handler;
013. import android.os.Message;
014. import android.view.View;
015. import android.widget.Button;
016. import android.widget.ProgressBar;
017. import android.widget.TextView;
018. import android.widget.Toast;
019. /\**
020. \*
021. \* @author Administrator
022. \*
023. \*/
024. public class SmartDownloadActivity extends Activity {
025. private ProgressBar downloadbar;
026. private TextView resultView;
027. private String path = ConstantValues.DOWNLOAD\_URL;
028. SmartFileDownloader loader;
029. private Handler handler = new Handler() {
030. @Override
031. // 信息
032. public void handleMessage(Message msg) {
033. switch (msg.what) {
034. case 1:
035. int size = msg.getData().getInt("size");
036. downloadbar.setProgress(size);
037. float result = (float) downloadbar.getProgress() / (float) downloadbar.getMax();
038. int p = (int) (result * 100);
039. resultView.setText(p + "%");
040. if (downloadbar.getProgress() == downloadbar.getMax())
041. Toast.makeText(SmartDownloadActivity.this, "下载成功", 1).show();
042. break;
043. case -1:
044. Toast.makeText(SmartDownloadActivity.this, msg.getData().getString("error"), 1).show();
045. break;
046. }
047. }
048. };
049. public void onCreate(Bundle savedInstanceState) {
050. super.onCreate(savedInstanceState);
051. setContentView(R.layout.download);
052. Button button = (Button) this.findViewById(R.id.button);
053. Button closeConn = (Button) findViewById(R.id.closeConn);
054. closeConn.setOnClickListener(new View.OnClickListener() {
055. @Override
056. public void onClick(View v) {
057. // TODO Auto-generated method stub
058. if(loader != null){
059. finish();
060. }else{
061. Toast.makeText(SmartDownloadActivity.this, "还没有开始下载，不能暂停", 1).show();
062. }
063. }
064. });
065. downloadbar = (ProgressBar) this.findViewById(R.id.downloadbar);
066. resultView = (TextView) this.findViewById(R.id.result);
067. resultView.setText(path);
068. button.setOnClickListener(new View.OnClickListener() {
069. @Override
070. public void onClick(View v) {
071. if (Environment.getExternalStorageState().equals(Environment.MEDIA\_MOUNTED)) {
072. download(path, ConstantValues.FILE\_PATH);
073. } else {
074. Toast.makeText(SmartDownloadActivity.this, "没有SDCard", 1).show();
075. }
076. }
077. });
078. }
079. // 对于UI控件的更新只能由主线程(UI线程)负责，如果在非UI线程更新UI控件，更新的结果不会反映在屏幕上，某些控件还会出错
080. private void download(final String path, final File dir) {
081. new Thread(new Runnable() {
082. @Override
083. public void run() {
084. try {
085. loader = new SmartFileDownloader(SmartDownloadActivity.this, path, dir, 3);
086. int length = loader.getFileSize();// 获取文件的长度
087. downloadbar.setMax(length);
088. loader.download(new SmartDownloadProgressListener() {
089. @Override
090. public void onDownloadSize(int size) {// 可以实时得到文件下载的长度
091. Message msg = new Message();
092. msg.what = 1;
093. msg.getData().putInt("size", size);
094. handler.sendMessage(msg);
095. }
096. });
097. } catch (Exception e) {
098. Message msg = new Message();// 信息提示
099. msg.what = -1;
100. msg.getData().putString("error", "下载失败");// 如果下载错误，显示提示失败！
101. handler.sendMessage(msg);
102. }
103. }
104. }).start();// 开始
105. }
106. }

*复制代码*

这个单个的下载线程  
SmartDownloadThread.java

Java代码

01. package com.hao.download;
02. import java.io.File;
03. import java.io.InputStream;
04. import java.io.RandomAccessFile;
05. import java.net.HttpURLConnection;
06. import java.net.URL;
07. import android.util.Log;
08. /\**
09. \* 线程下载
10. \* @author Administrator
11. \*
12. \*/
13. public class SmartDownloadThread extends Thread {
14. private static final String TAG = "SmartDownloadThread";
15. private File saveFile;
16. private URL downUrl;
17. private int block;
18. /*  \*下载开始位置 \*/
19. private int threadId = -1;
20. private int downLength;
21. private boolean finish = false;
22. private SmartFileDownloader downloader;
23. public SmartDownloadThread(SmartFileDownloader downloader, URL downUrl,
24. File saveFile, int block, int downLength, int threadId) {
25. this.downUrl = downUrl;
26. this.saveFile = saveFile;
27. this.block = block;
28. this.downloader = downloader;
29. this.threadId = threadId;
30. this.downLength = downLength;
31. }
32. @Override
33. public void run() {
34. if (downLength &lt; block) {// 未下载完成
35. try {
36. HttpURLConnection http = (HttpURLConnection) downUrl
37. .openConnection();
38. http.setConnectTimeout(5 * 1000);
39. http.setRequestMethod("GET");
40. http.setRequestProperty("Accept","image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, \*/\*");
41. http.setRequestProperty("Accept-Language", "zh-CN");
42. http.setRequestProperty("Referer", downUrl.toString());
43. http.setRequestProperty("Charset", "UTF-8");
44. int startPos = block * (threadId - 1) + downLength;// 开始位置
45. int endPos = block * threadId - 1;// 结束位置
46. http.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos);// 设置获取实体数据的范围
47. http.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
48. http.setRequestProperty("Connection", "Keep-Alive");
49. InputStream inStream = http.getInputStream();
50. byte\[] buffer = new byte\[1024];
51. int offset = 0;
52. print("Thread " + this.threadId + " start download from position " + startPos);
53. RandomAccessFile threadfile = new RandomAccessFile(this.saveFile, "rwd");
54. threadfile.seek(startPos);
55. while ((offset = inStream.read(buffer, 0, 1024)) != -1) {
56. threadfile.write(buffer, 0, offset);
57. downLength += offset;
58. downloader.update(this.threadId, downLength);
59. downloader.saveLogFile();
60. downloader.append(offset);
61. }
62. threadfile.close();
63. inStream.close();
64. print("Thread " + this.threadId + " download finish");
65. this.finish = true;
66. } catch (Exception e) {
67. this.downLength = -1;
68. print("Thread " + this.threadId + ":" + e);
69. }
70. }
71. }
72. private static void print(String msg) {
73. Log.i(TAG, msg);
74. }
75. /\**
76. \* 下载是否完成
77. \* @return
78. \*/
79. public boolean isFinish() {
80. return finish;
81. }
82. /\**
83. \* 已经下载的内容大小
84. \* @return 如果返回值为-1,代表下载失败
85. \*/
86. public long getDownLength() {
87. return downLength;
88. }
89. }

*复制代码*

总得下载线程  
SmartFileDownloader.java

Java代码

001. package com.hao.download;
002. import java.io.File;
003. import java.io.RandomAccessFile;
004. import java.net.HttpURLConnection;
005. import java.net.URL;
006. import java.util.LinkedHashMap;
007. import java.util.Map;
008. import java.util.UUID;
009. import java.util.concurrent.ConcurrentHashMap;
010. import java.util.regex.Matcher;
011. import java.util.regex.Pattern;
012. import com.hao.db.DownloadFileService;
013. import android.content.Context;
014. import android.util.Log;
015. /\**
016. \* 文件下载主程序
017. \* @author Administrator
018. \*
019. \*/
020. public class SmartFileDownloader {
021. private static final String TAG = "SmartFileDownloader";
022. private Context context;
023. private DownloadFileService fileService;
024. /* 已下载文件长度 \*/
025. private int downloadSize = 0;
026. /* 原始文件长度 \*/
027. private int fileSize = 0;
028. /\*原始文件名\*/
029. private String fileName;
030. /* 线程数 \*/
031. private SmartDownloadThread\[] threads;
032. /* 本地保存文件 \*/
033. private File saveFile;
034. /* 缓存各线程下载的长度 \*/
035. private Map&lt;Integer, Integer&gt; data = new ConcurrentHashMap&lt;Integer, Integer&gt;();
036. /* 每条线程下载的长度 \*/
037. private int block;
038. /* 下载路径 \*/
039. private String downloadUrl;
040. /\**
041. \* 获取文件名
042. \*/
043. public String getFileName(){
044. return this.fileName;
045. }
046. /\**
047. \* 获取线程数
048. \*/
049. public int getThreadSize() {
050. return threads.length;
051. }
052. /\**
053. \* 获取文件大小
054. \* @return
055. \*/
056. public int getFileSize() {
057. return fileSize;
058. }
059. /\**
060. \* 累计已下载大小
061. \* @param size
062. \*/
063. protected synchronized void append(int size) {
064. downloadSize += size;
065. }
066. /\**
067. \* 更新指定线程最后下载的位置
068. \* @param threadId 线程id
069. \* @param pos 最后下载的位置
070. \*/
071. protected void update(int threadId, int pos) {
072. this.data.put(threadId, pos);
073. }
074. /\**
075. \* 保存记录文件
076. \*/
077. protected synchronized void saveLogFile() {
078. this.fileService.update(this.downloadUrl, this.data);
079. }
080. /\**
081. \* 构建文件下载器
082. \* @param downloadUrl 下载路径
083. \* @param fileSaveDir 文件保存目录
084. \* @param threadNum 下载线程数
085. \*/
086. public SmartFileDownloader(Context context, String downloadUrl,
087. File fileSaveDir, int threadNum) {
088. try {
089. this.context = context;
090. this.downloadUrl = downloadUrl;
091. fileService = new DownloadFileService(this.context);
092. URL url = new URL(this.downloadUrl);
093. if (!fileSaveDir.exists()) fileSaveDir.mkdirs();
094. this.threads = new SmartDownloadThread\[threadNum];
095. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
096. conn.setConnectTimeout(5 * 1000);
097. conn.setRequestMethod("GET");
098. conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, \*/\*");
099. conn.setRequestProperty("Accept-Language", "zh-CN");
100. conn.setRequestProperty("Referer", downloadUrl);
101. conn.setRequestProperty("Charset", "UTF-8");
102. conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
103. conn.setRequestProperty("Connection", "Keep-Alive");
104. conn.connect();
105. printResponseHeader(conn);
106. if (conn.getResponseCode() == 200) {
107. this.fileSize = conn.getContentLength();// 根据响应获取文件大小
108. if (this.fileSize &lt;= 0)
109. throw new RuntimeException("Unkown file size ");
110. fileName = getFileName(conn);
111. this.saveFile = new File(fileSaveDir, fileName);/* 保存文件 \*/
112. Map&lt;Integer, Integer&gt; logdata = fileService.getData(downloadUrl);
113. if (logdata.size() &gt; 0) {
114. for (Map.Entry&lt;Integer, Integer&gt; entry : logdata.entrySet())
115. data.put(entry.getKey(), entry.getValue());
116. }
117. //划分每个线程下载文件长度
118. this.block = (this.fileSize % this.threads.length) == 0 ? this.fileSize / this.threads.length
119. : this.fileSize / this.threads.length + 1;
120. if (this.data.size() == this.threads.length) {
121. for (int i = 0; i &lt; this.threads.length; i++) {
122. this.downloadSize += this.data.get(i + 1);
123. }
124. print("已经下载的长度" + this.downloadSize);
125. }
126. } else {
127. throw new RuntimeException("server no response ");
128. }
129. } catch (Exception e) {
130. print(e.toString());
131. throw new RuntimeException("don't connection this url");
132. }
133. }
134. /\**
135. \* 获取文件名
136. \*/
137. private String getFileName(HttpURLConnection conn) {
138. String filename = this.downloadUrl.substring(this.downloadUrl.lastIndexOf('/') + 1);//链接的最后一个/就是文件名
139. if (filename == null || "".equals(filename.trim())) {// 如果获取不到文件名称
140. for (int i = 0;; i++) {
141. String mine = conn.getHeaderField(i);
142. print("ConnHeader:"+mine+" ");
143. if (mine == null)
144. break;
145. if ("content-disposition".equals(conn.getHeaderFieldKey(i).toLowerCase())) {
146. Matcher m = Pattern.compile(".\*filename=(.\*)").matcher(mine.toLowerCase());
147. if (m.find())
148. return m.group(1);
149. }
150. }
151. filename = UUID.randomUUID() + ".tmp";// 默认取一个文件名
152. }
153. return filename;
154. }
155. /\**
156. \* 开始下载文件
157. \*
158. \* @param listener
159. *            监听下载数量的变化,如果不需要了解实时下载的数量,可以设置为null
160. \* @return 已下载文件大小
161. \* @throws Exception
162. \*/
163. public int download(SmartDownloadProgressListener listener)
164. throws Exception {
165. try {
166. RandomAccessFile randOut = new RandomAccessFile(this.saveFile, "rw");
167. if (this.fileSize &gt; 0)
168. randOut.setLength(this.fileSize);
169. randOut.close();
170. URL url = new URL(this.downloadUrl);
171. if (this.data.size() != this.threads.length) {
172. this.data.clear();// 清除数据
173. for (int i = 0; i &lt; this.threads.length; i++) {
174. this.data.put(i + 1, 0);
175. }
176. }
177. for (int i = 0; i &lt; this.threads.length; i++) {
178. int downLength = this.data.get(i + 1);
179. if (downLength &lt; this.block && this.downloadSize &lt; this.fileSize) { // 该线程未完成下载时,继续下载
180. this.threads\[i] = new SmartDownloadThread(this, url,
181. this.saveFile, this.block, this.data.get(i + 1), i + 1);
182. this.threads\[i].setPriority(7);
183. this.threads\[i].start();
184. } else {
185. this.threads\[i] = null;
186. }
187. }
188. this.fileService.save(this.downloadUrl, this.data);
189. boolean notFinish = true;// 下载未完成
190. while (notFinish) {// 循环判断是否下载完毕
191. Thread.sleep(900);
192. notFinish = false;// 假定下载完成
193. for (int i = 0; i &lt; this.threads.length; i++) {
194. if (this.threads\[i] != null && !this.threads\[i].isFinish()) {
195. notFinish = true;// 下载没有完成
196. if (this.threads\[i].getDownLength() == -1) {// 如果下载失败,再重新下载
197. this.threads\[i] = new SmartDownloadThread(this,
198. url, this.saveFile, this.block, this.data.get(i + 1), i + 1);
199. this.threads\[i].setPriority(7);
200. this.threads\[i].start();
201. }
202. }
203. }
204. if (listener != null)
205. listener.onDownloadSize(this.downloadSize);
206. }
207. fileService.delete(this.downloadUrl);
208. } catch (Exception e) {
209. print(e.toString());
210. throw new Exception("file download fail");
211. }
212. return this.downloadSize;
213. }
214. /\**
215. \* 获取Http响应头字段
216. \*
217. \* @param http
218. \* @return
219. \*/
220. public static Map&lt;String, String&gt; getHttpResponseHeader(
221. HttpURLConnection http) {
222. Map&lt;String, String&gt; header = new LinkedHashMap&lt;String, String&gt;();
223. for (int i = 0;; i++) {
224. String mine = http.getHeaderField(i);
225. if (mine == null)
226. break;
227. header.put(http.getHeaderFieldKey(i), mine);
228. }
229. return header;
230. }
231. /\**
232. \* 打印Http头字段
233. \*
234. \* @param http
235. \*/
236. public static void printResponseHeader(HttpURLConnection http) {
237. Map&lt;String, String&gt; header = getHttpResponseHeader(http);
238. for (Map.Entry&lt;String, String&gt; entry : header.entrySet()) {
239. String key = entry.getKey() != null ? entry.getKey() + ":" : "";
240. print(key + entry.getValue());
241. }
242. }
243. // 打印日志
244. private static void print(String msg) {
245. Log.i(TAG, msg);
246. }
247. public interface SmartDownloadProgressListener {
248. public void onDownloadSize(int size);
249. }
250. }

*复制代码*

好了这里只是将主要的代码分享出来，主要是为了了解他的基本流程，然后自己可以扩展，和优化