`
hecal
  • 浏览: 74712 次
社区版块
存档分类
最新评论

<转载>andriod 断点续传和下载原理分析

 
阅读更多

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

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

333.jpg


关键代码:

FileServer.java

Java代码

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.io.PushbackInputStream;
  8. import java.io.RandomAccessFile;
  9. import java.net.ServerSocket;
  10. import java.net.Socket;
  11. import java.text.SimpleDateFormat;
  12. import java.util.Date;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. import java.util.Properties;
  16. import java.util.Set;
  17. import java.util.concurrent.ExecutorService;
  18. import java.util.concurrent.Executors;

  19. import util.FileLogInfo;
  20. import util.StreamTool;



  21. public class FileServer {
  22.          private ExecutorService executorService;//线程池
  23.          private int port;//监听端口
  24.          private boolean quit = false;//退出
  25.          private ServerSocket server;
  26.          private Map<Long, FileLogInfo> datas = new HashMap<Long, FileLogInfo>();//存放断点数据,以后改为数据库存放
  27.          public FileServer(int port)
  28.          {
  29.                  this.port = port;
  30.                  //创建线程池,池中具有(cpu个数*50)条线程
  31.                  executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 50);
  32.          }
  33.          
  34.         /**
  35.           * 退出
  36.           */
  37.          public void quit()
  38.          {
  39.                 this.quit = true;
  40.                 try
  41.                 {
  42.                         server.close();
  43.                 }catch (IOException e)
  44.                 {
  45.                         e.printStackTrace();
  46.                 }
  47.          }
  48.          
  49.          /**
  50.           * 启动服务
  51.           * @throws Exception
  52.           */
  53.          public void start() throws Exception
  54.          {
  55.                  server = new ServerSocket(port);//实现端口监听
  56.                  while(!quit)
  57.                  {
  58.                  try
  59.                  {
  60.                    Socket socket = server.accept();
  61.                    executorService.execute(new SocketTask(socket));//为支持多用户并发访问,采用线程池管理每一个用户的连接请求
  62.                  }catch (Exception e)
  63.                  {
  64.                      e.printStackTrace();
  65.                  }
  66.              }
  67.          }
  68.          
  69.          private final class SocketTask implements Runnable
  70.          {
  71.                 private Socket socket = null;
  72.                 public SocketTask(Socket socket)
  73.                 {
  74.                         this.socket = socket;
  75.                 }
  76.                 @Override
  77.                 public void run()
  78.                 {
  79.                         try
  80.                         {
  81.                                 System.out.println("FileServer accepted connection "+ socket.getInetAddress()+ ":"+ socket.getPort());
  82.                                 //得到客户端发来的第一行协议数据:Content-Length=143253434;filename=xxx.3gp;sourceid=
  83.                                 //如果用户初次上传文件,sourceid的值为空。
  84.                                 InputStream inStream = socket.getInputStream();
  85.                                 String head = StreamTool.readLine(inStream);
  86.                                 System.out.println("FileServer head:"+head);
  87.                                 if(head!=null)
  88.                                 {
  89.                                         //下面从协议数据中提取各项参数值
  90.                                         String[] items = head.split(";");
  91.                                         String filelength = items[0].substring(items[0].indexOf("=")+1);
  92.                                         String filename = items[1].substring(items[1].indexOf("=")+1);
  93.                                         String sourceid = items[2].substring(items[2].indexOf("=")+1);               
  94.                                         //生成资源id,如果需要唯一性,可以采用UUID
  95.                                         long id = System.currentTimeMillis();
  96.                                         FileLogInfo log = null;
  97.                                         if(sourceid!=null && !"".equals(sourceid))
  98.                                         {
  99.                                                 id = Long.valueOf(sourceid);
  100.                                                 //查找上传的文件是否存在上传记录
  101.                                                 log = find(id);
  102.                                         }
  103.                                         File file = null;
  104.                                         int position = 0;
  105.                                         //如果上传的文件不存在上传记录,为文件添加跟踪记录
  106.                                         if(log==null)
  107.                                         {
  108.                                                 //设置存放的位置与当前应用的位置有关
  109.                                                 File dir = new File("c:/temp/");
  110.                                                 if(!dir.exists()) dir.mkdirs();
  111.                                                 file = new File(dir, filename);
  112.                                                 //如果上传的文件发生重名,然后进行改名
  113.                                                 if(file.exists())
  114.                                                 {
  115.                                                         filename = filename.substring(0, filename.indexOf(".")-1)+ dir.listFiles().length+ filename.substring(filename.indexOf("."));
  116.                                                         file = new File(dir, filename);
  117.                                                 }
  118.                                                 save(id, file);
  119.                                         }
  120.                                         // 如果上传的文件存在上传记录,读取上次的断点位置
  121.                                         else
  122.                                         {
  123.                                                 System.out.println("FileServer have exits log not null");
  124.                                                 //从上传记录中得到文件的路径
  125.                                                 file = new File(log.getPath());
  126.                                                 if(file.exists())
  127.                                                 {
  128.                                                         File logFile = new File(file.getParentFile(), file.getName()+".log");
  129.                                                         if(logFile.exists())
  130.                                                         {
  131.                                                                 Properties properties = new Properties();
  132.                                                                 properties.load(new FileInputStream(logFile));
  133.                                                                 //读取断点位置
  134.                                                                 position = Integer.valueOf(properties.getProperty("length"));
  135.                                                         }
  136.                                                 }
  137.                                         }
  138.                                         //***************************上面是对协议头的处理,下面正式接收数据***************************************
  139.                                         //向客户端请求传输数据
  140.                                         OutputStream outStream = socket.getOutputStream();
  141.                                         String response = "sourceid="+ id+ ";position="+ position+ "%";
  142.                                         //服务器收到客户端的请求信息后,给客户端返回响应信息:sourceid=1274773833264;position=position
  143.                                         //sourceid由服务生成,唯一标识上传的文件,position指示客户端从文件的什么位置开始上传
  144.                                         outStream.write(response.getBytes());
  145.                                         RandomAccessFile fileOutStream = new RandomAccessFile(file, "rwd");
  146.                                         //设置文件长度
  147.                                         if(position==0) fileOutStream.setLength(Integer.valueOf(filelength));
  148.                                         //移动文件指定的位置开始写入数据
  149.                                         fileOutStream.seek(position);
  150.                                         byte[] buffer = new byte[1024];
  151.                                         int len = -1;
  152.                                         int length = position;
  153.                                         //从输入流中读取数据写入到文件中,并将已经传入的文件长度写入配置文件,实时记录文件的最后保存位置
  154.                                         while( (len=inStream.read(buffer)) != -1)
  155.                                         {
  156.                                                 fileOutStream.write(buffer, 0, len);
  157.                                                 length += len;
  158.                                                 Properties properties = new Properties();
  159.                                                 properties.put("length", String.valueOf(length));
  160.                                                 FileOutputStream logFile = new FileOutputStream(new File(file.getParentFile(), file.getName()+".log"));
  161.                                                 //实时记录文件的最后保存位置
  162.                                                 properties.store(logFile, null);
  163.                                                 logFile.close();
  164.                                         }
  165.                                         //如果长传长度等于实际长度则表示长传成功
  166.                                         if(length==fileOutStream.length()){
  167.                                                 delete(id);
  168.                                         }
  169.                                         fileOutStream.close();                                       
  170.                                         inStream.close();
  171.                                         outStream.close();
  172.                                         file = null;
  173.                                 }
  174.                         }
  175.                         catch (Exception e)
  176.                         {
  177.                                 e.printStackTrace();
  178.                         }
  179.                         finally{
  180.                     try
  181.                     {
  182.                         if(socket!=null && !socket.isClosed()) socket.close();
  183.                     }
  184.                     catch (IOException e)
  185.                     {
  186.                             e.printStackTrace();
  187.                     }
  188.                 }
  189.                 }
  190.          }
  191.          
  192.          /**
  193.           * 查找在记录中是否有sourceid的文件
  194.           * @param sourceid
  195.           * @return
  196.           */
  197.          public FileLogInfo find(Long sourceid)
  198.          {
  199.                  return datas.get(sourceid);
  200.          }
  201.          
  202.          /**
  203.           * 保存上传记录,日后可以改成通过数据库存放
  204.           * @param id
  205.           * @param saveFile
  206.           */
  207.          public void save(Long id, File saveFile)
  208.          {
  209.                  System.out.println("save logfile "+id);
  210.                  datas.put(id, new FileLogInfo(id, saveFile.getAbsolutePath()));
  211.          }
  212.          
  213.          /**
  214.           * 当文件上传完毕,删除记录
  215.           * @param sourceid
  216.           */
  217.          public void delete(long sourceid)
  218.          {
  219.                  System.out.println("delete logfile "+sourceid);
  220.                  if(datas.containsKey(sourceid)) datas.remove(sourceid);
  221.          }
  222.          
  223. }
复制代码

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

222.jpg


关键代码:
UploadActivity.java

Java代码

  1. package com.hao;

  2. import java.io.File;
  3. import java.util.List;

  4. import com.hao.upload.UploadThread;
  5. import com.hao.upload.UploadThread.UploadProgressListener;
  6. import com.hao.util.ConstantValues;
  7. import com.hao.util.FileBrowserActivity;

  8. import android.app.Activity;
  9. import android.app.Dialog;
  10. import android.app.ProgressDialog;
  11. import android.content.DialogInterface;
  12. import android.content.Intent;
  13. import android.content.res.Resources;
  14. import android.net.Uri;
  15. import android.os.Bundle;
  16. import android.os.Environment;
  17. import android.os.Handler;
  18. import android.os.Message;
  19. import android.util.Log;
  20. import android.view.View;
  21. import android.view.View.OnClickListener;
  22. import android.widget.Button;
  23. import android.widget.TextView;
  24. import android.widget.Toast;
  25. /**
  26. *
  27. * @author Administrator
  28. *
  29. */
  30. public class UploadActivity extends Activity implements OnClickListener{
  31.         private static final String TAG = "SiteFileFetchActivity";
  32.         private Button download, upload, select_file;
  33.         private TextView info;
  34.         private static final int PROGRESS_DIALOG = 0;
  35.         private ProgressDialog progressDialog;
  36.         private UploadThread uploadThread;
  37.         private String uploadFilePath = null;
  38.         private String fileName;
  39.     /** Called when the activity is first created. */
  40.     @Override
  41.     public void onCreate(Bundle savedInstanceState) {
  42.         super.onCreate(savedInstanceState);
  43.         setContentView(R.layout.upload);
  44.         initView();
  45.     }
  46.    
  47.         private void initView(){
  48.             download = (Button) findViewById(R.id.download);
  49.             download.setOnClickListener(this);
  50.             upload = (Button) findViewById(R.id.upload);
  51.             upload.setOnClickListener(this);
  52.             info = (TextView) findViewById(R.id.info);
  53.             select_file = (Button) findViewById(R.id.select_file);
  54.             select_file.setOnClickListener(this);
  55.     }
  56.        
  57.         @Override
  58.         protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  59.                 // TODO Auto-generated method stub
  60.                 super.onActivityResult(requestCode, resultCode, data);
  61.         if (resultCode == RESULT_OK) {
  62.                   if (requestCode == 1) {
  63.                            Uri uri = data.getData();    // 接收用户所选文件的路径
  64.                            info.setText("select: " + uri); // 在界面上显示路径
  65.                            uploadFilePath = uri.getPath();
  66.                            int last = uploadFilePath.lastIndexOf("/");
  67.                            uploadFilePath = uri.getPath().substring(0, last+1);
  68.                            fileName = uri.getLastPathSegment();
  69.                   }
  70.         }
  71.         }
  72.    
  73.     protected Dialog onCreateDialog(int id) {
  74.         switch(id) {
  75.         case PROGRESS_DIALOG:
  76.             progressDialog = new ProgressDialog(UploadActivity.this);
  77.             progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  78.             progressDialog.setButton("暂停", new DialogInterface.OnClickListener() {
  79.                                 @Override
  80.                                 public void onClick(DialogInterface dialog, int which) {
  81.                                         // TODO Auto-generated method stub
  82.                                         uploadThread.closeLink();
  83.                                         dialog.dismiss();
  84.                                 }
  85.                         });
  86.             progressDialog.setMessage("正在上传...");
  87.             progressDialog.setMax(100);
  88.             return progressDialog;
  89.         default:
  90.             return null;
  91.         }
  92.     }
  93.    
  94.     /**
  95.      * 使用Handler给创建他的线程发送消息,
  96.      * 匿名内部类
  97.      */  
  98.     private Handler handler = new Handler()  
  99.     {  
  100.             @Override
  101.         public void handleMessage(Message msg)   
  102.         {  
  103.             //获得上传长度的进度  
  104.             int length = msg.getData().getInt("size");  
  105.             progressDialog.setProgress(length);  
  106.             if(progressDialog.getProgress()==progressDialog.getMax())//上传成功  
  107.             {  
  108.                     progressDialog.dismiss();
  109.                 Toast.makeText(UploadActivity.this, getResources().getString(R.string.upload_over), 1).show();  
  110.             }  
  111.         }  
  112.     };   

  113.         @Override
  114.         public void onClick(View v) {
  115.                 // TODO Auto-generated method stub
  116.                 Resources r = getResources();
  117.                 switch(v.getId()){
  118.                         case R.id.select_file:
  119.                                 Intent intent = new Intent();
  120.                                 //设置起始目录和查找的类型
  121.                         intent.setDataAndType(Uri.fromFile(new File("/sdcard")), "*/*");//"*/*"表示所有类型,设置起始文件夹和文件类型
  122.                         intent.setClass(UploadActivity.this, FileBrowserActivity.class);
  123.                         startActivityForResult(intent, 1);
  124.                                 break;
  125.                         case R.id.download:
  126.                                 startActivity(new Intent(UploadActivity.this, SmartDownloadActivity.class));
  127.                                 break;
  128.                         case R.id.upload:
  129.                 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))//判断SDCard是否存在  
  130.                 {  
  131.                         if(uploadFilePath == null){
  132.                                 Toast.makeText(UploadActivity.this, "还没设置上传文件", 1).show();
  133.                         }
  134.                         System.out.println("uploadFilePath:"+uploadFilePath+" "+fileName);
  135.                     //取得SDCard的目录  
  136.                     File uploadFile = new File(new File(uploadFilePath), fileName);  
  137.                     Log.i(TAG, "filePath:"+uploadFile.toString());
  138.                     if(uploadFile.exists())  
  139.                     {  
  140.                         showDialog(PROGRESS_DIALOG);
  141.                         info.setText(uploadFile+" "+ConstantValues.HOST+":"+ConstantValues.PORT);
  142.                                     progressDialog.setMax((int) uploadFile.length());//设置长传文件的最大刻度
  143.                             uploadThread = new UploadThread(UploadActivity.this, uploadFile, ConstantValues.HOST, ConstantValues.PORT);
  144.                             uploadThread.setListener(new UploadProgressListener() {
  145.                                                        
  146.                                                         @Override
  147.                                                         public void onUploadSize(int size) {
  148.                                                                 // TODO Auto-generated method stub
  149.                                                                 Message msg = new Message();
  150.                                                                 msg.getData().putInt("size", size);
  151.                                                                 handler.sendMessage(msg);
  152.                                                         }
  153.                                                 });
  154.                             uploadThread.start();
  155.                     }  
  156.                     else  
  157.                     {  
  158.                         Toast.makeText(UploadActivity.this, "文件不存在", 1).show();  
  159.                     }  
  160.                 }  
  161.                 else  
  162.                 {  
  163.                     Toast.makeText(UploadActivity.this, "SDCard不存在!", 1).show();  
  164.                 }  
  165.                                 break;
  166.                 }
  167.                        
  168.         }
  169.        
  170.        
  171. }
复制代码

UploadThread.java

Java代码

  1. package com.hao.upload;

  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.io.RandomAccessFile;
  7. import java.net.Socket;

  8. import android.content.Context;
  9. 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.        
  32.         public void setListener(UploadProgressListener listener) {
  33.                 this.listener = listener;
  34.         }

  35.         /**
  36.          * 模拟断开连接
  37.          */
  38.         public void closeLink(){
  39.                 try{
  40.                         if(socket != null) socket.close();
  41.                 }catch(IOException e){
  42.                         e.printStackTrace();
  43.                         Log.e(TAG, "close socket fail");
  44.                 }
  45.         }

  46.         @Override
  47.         public void run() {
  48.                 // TODO Auto-generated method stub
  49.                 try {
  50.                         // 判断文件是否已有上传记录
  51.                         String souceid = logService.getBindId(uploadFile);
  52.                         // 构造拼接协议
  53.                         String head = "Content-Length=" + uploadFile.length()
  54.                                         + ";filename=" + uploadFile.getName() + ";sourceid="
  55.                                         + (souceid == null ? "" : souceid) + "%";
  56.                         // 通过Socket取得输出流
  57.                         socket = new Socket(dstName, dstPort);
  58.                         OutputStream outStream = socket.getOutputStream();
  59.                         outStream.write(head.getBytes());
  60.                         Log.i(TAG, "write to outStream");

  61.                         InputStream inStream = socket.getInputStream();
  62.                         // 获取到字符流的id与位置
  63.                         String response = StreamTool.readLine(inStream);
  64.                         Log.i(TAG, "response:" + response);
  65.                         String[] items = response.split(";");
  66.                         String responseid = items[0].substring(items[0].indexOf("=") + 1);
  67.                         String position = items[1].substring(items[1].indexOf("=") + 1);
  68.                         // 代表原来没有上传过此文件,往数据库添加一条绑定记录
  69.                         if (souceid == null) {
  70.                                 logService.save(responseid, uploadFile);
  71.                         }
  72.                         RandomAccessFile fileOutStream = new RandomAccessFile(uploadFile, "r");
  73.                         // 查找上次传送的最终位置,并从这开始传送
  74.                         fileOutStream.seek(Integer.valueOf(position));
  75.                         byte[] buffer = new byte[1024];
  76.                         int len = -1;
  77.                         // 初始化上传的数据长度
  78.                         int length = Integer.valueOf(position);
  79.                         while ((len = fileOutStream.read(buffer)) != -1) {
  80.                                 outStream.write(buffer, 0, len);
  81.                                 // 设置长传数据长度
  82.                                 length += len;
  83.                                 listener.onUploadSize(length);
  84.                         }
  85.                         fileOutStream.close();
  86.                         outStream.close();
  87.                         inStream.close();
  88.                         socket.close();
  89.                         // 判断上传完则删除数据
  90.                         if (length == uploadFile.length())
  91.                                 logService.delete(uploadFile);
  92.                 } catch (Exception e) {
  93.                         e.printStackTrace();
  94.                 }
  95.         }
  96.        
  97.         public interface UploadProgressListener{
  98.                 void onUploadSize(int size);
  99.         }
  100. }
复制代码

下面是多线程下载

111.jpg


SmartDownloadActivity.java

Java代码

  1. package com.hao;

  2. import java.io.File;

  3. import com.hao.R;
  4. import com.hao.R.id;
  5. import com.hao.R.layout;
  6. import com.hao.download.SmartFileDownloader;
  7. import com.hao.download.SmartFileDownloader.SmartDownloadProgressListener;
  8. import com.hao.util.ConstantValues;

  9. import android.app.Activity;
  10. import android.os.Bundle;
  11. import android.os.Environment;
  12. import android.os.Handler;
  13. import android.os.Message;
  14. import android.view.View;
  15. import android.widget.Button;
  16. import android.widget.ProgressBar;
  17. import android.widget.TextView;
  18. import android.widget.Toast;

  19. /**
  20. *
  21. * @author Administrator
  22. *
  23. */
  24. public class SmartDownloadActivity extends Activity {
  25.         private ProgressBar downloadbar;
  26.         private TextView resultView;
  27.         private String path = ConstantValues.DOWNLOAD_URL;
  28.         SmartFileDownloader loader;
  29.         private Handler handler = new Handler() {
  30.                 @Override
  31.                 // 信息
  32.                 public void handleMessage(Message msg) {
  33.                         switch (msg.what) {
  34.                         case 1:
  35.                                 int size = msg.getData().getInt("size");
  36.                                 downloadbar.setProgress(size);
  37.                                 float result = (float) downloadbar.getProgress() / (float) downloadbar.getMax();
  38.                                 int p = (int) (result * 100);
  39.                                 resultView.setText(p + "%");
  40.                                 if (downloadbar.getProgress() == downloadbar.getMax())
  41.                                         Toast.makeText(SmartDownloadActivity.this, "下载成功", 1).show();
  42.                                 break;
  43.                         case -1:
  44.                                 Toast.makeText(SmartDownloadActivity.this, msg.getData().getString("error"), 1).show();
  45.                                 break;
  46.                         }

  47.                 }
  48.         };

  49.         public void onCreate(Bundle savedInstanceState) {
  50.                 super.onCreate(savedInstanceState);
  51.                 setContentView(R.layout.download);

  52.                 Button button = (Button) this.findViewById(R.id.button);
  53.                 Button closeConn = (Button) findViewById(R.id.closeConn);
  54.                 closeConn.setOnClickListener(new View.OnClickListener() {
  55.                        
  56.                         @Override
  57.                         public void onClick(View v) {
  58.                                 // TODO Auto-generated method stub
  59.                                 if(loader != null){
  60.                                         finish();
  61.                                 }else{
  62.                                         Toast.makeText(SmartDownloadActivity.this, "还没有开始下载,不能暂停", 1).show();
  63.                                 }
  64.                         }
  65.                 });
  66.                 downloadbar = (ProgressBar) this.findViewById(R.id.downloadbar);
  67.                 resultView = (TextView) this.findViewById(R.id.result);
  68.                 resultView.setText(path);
  69.                 button.setOnClickListener(new View.OnClickListener() {
  70.                         @Override
  71.                         public void onClick(View v) {
  72.                                 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
  73.                                         download(path, ConstantValues.FILE_PATH);
  74.                                 } else {
  75.                                         Toast.makeText(SmartDownloadActivity.this, "没有SDCard", 1).show();
  76.                                 }
  77.                         }
  78.                 });
  79.         }

  80.         // 对于UI控件的更新只能由主线程(UI线程)负责,如果在非UI线程更新UI控件,更新的结果不会反映在屏幕上,某些控件还会出错
  81.         private void download(final String path, final File dir) {
  82.                 new Thread(new Runnable() {
  83.                         @Override
  84.                         public void run() {
  85.                                 try {
  86.                                         loader = new SmartFileDownloader(SmartDownloadActivity.this, path, dir, 3);
  87.                                         int length = loader.getFileSize();// 获取文件的长度
  88.                                         downloadbar.setMax(length);
  89.                                         loader.download(new SmartDownloadProgressListener() {
  90.                                                 @Override
  91.                                                 public void onDownloadSize(int size) {// 可以实时得到文件下载的长度
  92.                                                         Message msg = new Message();
  93.                                                         msg.what = 1;
  94.                                                         msg.getData().putInt("size", size);
  95.                                                         handler.sendMessage(msg);
  96.                                                 }
  97.                                         });
  98.                                 } catch (Exception e) {
  99.                                         Message msg = new Message();// 信息提示
  100.                                         msg.what = -1;
  101.                                         msg.getData().putString("error", "下载失败");// 如果下载错误,显示提示失败!
  102.                                         handler.sendMessage(msg);
  103.                                 }
  104.                         }
  105.                 }).start();// 开始

  106.         }
  107. }
复制代码

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

Java代码

  1. package com.hao.download;

  2. import java.io.File;
  3. import java.io.InputStream;
  4. import java.io.RandomAccessFile;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;

  7. import android.util.Log;

  8. /**
  9. * 线程下载
  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 < 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代码

  1. package com.hao.download;

  2. import java.io.File;
  3. import java.io.RandomAccessFile;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6. import java.util.LinkedHashMap;
  7. import java.util.Map;
  8. import java.util.UUID;
  9. import java.util.concurrent.ConcurrentHashMap;
  10. import java.util.regex.Matcher;
  11. import java.util.regex.Pattern;

  12. import com.hao.db.DownloadFileService;

  13. import android.content.Context;
  14. import android.util.Log;

  15. /**
  16. * 文件下载主程序
  17. * @author Administrator
  18. *
  19. */
  20. public class SmartFileDownloader {
  21.         private static final String TAG = "SmartFileDownloader";
  22.         private Context context;
  23.         private DownloadFileService fileService;
  24.         /* 已下载文件长度 */
  25.         private int downloadSize = 0;
  26.         /* 原始文件长度 */
  27.         private int fileSize = 0;
  28.         /*原始文件名*/
  29.         private String fileName;
  30.         /* 线程数 */
  31.         private SmartDownloadThread[] threads;
  32.         /* 本地保存文件 */
  33.         private File saveFile;
  34.         /* 缓存各线程下载的长度 */
  35.         private Map<Integer, Integer> data = new ConcurrentHashMap<Integer, Integer>();
  36.         /* 每条线程下载的长度 */
  37.         private int block;
  38.         /* 下载路径 */
  39.         private String downloadUrl;

  40.         /**
  41.          * 获取文件名
  42.          */
  43.         public String getFileName(){
  44.                 return this.fileName;
  45.         }
  46.         /**
  47.          * 获取线程数
  48.          */
  49.         public int getThreadSize() {
  50.                 return threads.length;
  51.         }

  52.         /**
  53.          * 获取文件大小
  54.          * @return
  55.          */
  56.         public int getFileSize() {
  57.                 return fileSize;
  58.         }

  59.         /**
  60.          * 累计已下载大小
  61.          * @param size
  62.          */
  63.         protected synchronized void append(int size) {
  64.                 downloadSize += size;
  65.         }

  66.         /**
  67.          * 更新指定线程最后下载的位置
  68.          * @param threadId 线程id
  69.          * @param pos 最后下载的位置
  70.          */
  71.         protected void update(int threadId, int pos) {
  72.                 this.data.put(threadId, pos);
  73.         }

  74.         /**
  75.          * 保存记录文件
  76.          */
  77.         protected synchronized void saveLogFile() {
  78.                 this.fileService.update(this.downloadUrl, this.data);
  79.         }

  80.         /**
  81.          * 构建文件下载器
  82.          * @param downloadUrl 下载路径
  83.          * @param fileSaveDir 文件保存目录
  84.          * @param threadNum 下载线程数
  85.          */
  86.         public SmartFileDownloader(Context context, String downloadUrl,
  87.                         File fileSaveDir, int threadNum) {
  88.                 try {
  89.                         this.context = context;
  90.                         this.downloadUrl = downloadUrl;
  91.                         fileService = new DownloadFileService(this.context);
  92.                         URL url = new URL(this.downloadUrl);
  93.                         if (!fileSaveDir.exists()) fileSaveDir.mkdirs();
  94.                         this.threads = new SmartDownloadThread[threadNum];
  95.                         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  96.                         conn.setConnectTimeout(5 * 1000);
  97.                         conn.setRequestMethod("GET");
  98.                         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, */*");
  99.                         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 <= 0)
  109.                                         throw new RuntimeException("Unkown file size ");

  110.                                 fileName = getFileName(conn);
  111.                                 this.saveFile = new File(fileSaveDir, fileName);/* 保存文件 */
  112.                                 Map<Integer, Integer> logdata = fileService.getData(downloadUrl);
  113.                                 if (logdata.size() > 0) {
  114.                                         for (Map.Entry<Integer, Integer> 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 < 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 > 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 < this.threads.length; i++) {
  174.                                         this.data.put(i + 1, 0);
  175.                                 }
  176.                         }
  177.                         for (int i = 0; i < this.threads.length; i++) {
  178.                                 int downLength = this.data.get(i + 1);
  179.                                 if (downLength < this.block && this.downloadSize < 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 < 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<String, String> getHttpResponseHeader(
  221.                         HttpURLConnection http) {
  222.                 Map<String, String> header = new LinkedHashMap<String, String>();
  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<String, String> header = getHttpResponseHeader(http);
  238.                 for (Map.Entry<String, String> 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. }
复制代码

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

  • 大小: 40.4 KB
  • 大小: 38.9 KB
  • 大小: 34.4 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics