`
andy_叶
  • 浏览: 67969 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Android下使用Http协议实现多线程断点续传下载

 
阅读更多

0.使用多线程下载会提升文件下载的速度,那么多线程下载文件的过程是:

(1)首先获得下载文件的长度,然后设置本地文件的长度

    HttpURLConnection.getContentLength();

    RandomAccessFile file = new RandomAccessFile("QQWubiSetup.exe","rwd");

    file.setLength(filesize);//设置本地文件的长度

(2)根据文件长度和线程数计算每条线程下载的数据长度和下载位置。

    如:文件的长度为6M,线程数为3,那么,每条线程下载的数据长度为2M,每条线程开始下载的位置如下图所示。

     例如10M大小,使用3个线程来下载,

     线程下载的数据长度   (10%3 == 0 ? 10/3:10/3+1) ,第1,2个线程下载长度是4M,第三个线程下载长度为2M

     下载开始位置:线程id*每条线程下载的数据长度 = ?

     下载结束位置:(线程id+1)*每条线程下载的数据长度-1=?

(3)使用HttpRange头字段指定每条线程从文件的什么位置开始下载,下载到什么位置为止,

     如:指定从文件的2M位置开始下载,下载到位置(4M-1byte)为止

    代码如下:HttpURLConnection.setRequestProperty("Range", "bytes=2097152-4194303");

(4)保存文件,使用RandomAccessFile类指定每条线程从本地文件的什么位置开始写入数据。

RandomAccessFile threadfile = new RandomAccessFile("QQWubiSetup.exe ","rwd");

threadfile.seek(2097152);//从文件的什么位置开始写入数据

 

1.多线程下载的核心代码示例

  1. public class MulThreadDownload   
  2. {  
  3.     /** 
  4.      * 多线程下载 
  5.      * @param args 
  6.      */  
  7.     public static void main(String[] args)   
  8.     {  
  9.         String path = "http://net.hoo.com/QQWubiSetup.exe";  
  10.         try   
  11.         {  
  12.             new MulThreadDownload().download(path, 3);  
  13.         }  
  14.         catch (Exception e)   
  15.         {  
  16.             e.printStackTrace();  
  17.         }  
  18.     }  
  19.     /** 
  20.      * 从路径中获取文件名称 
  21.      * @param path 下载路径 
  22.      * @return 
  23.      */  
  24.     public static String getFilename(String path)  
  25.     {  
  26.         return path.substring(path.lastIndexOf('/')+1);  
  27.     }  
  28.     /** 
  29.      * 下载文件 
  30.      * @param path 下载路径 
  31.      * @param threadsize 线程数 
  32.      */  
  33.     public void download(String path, int threadsize) throws Exception  
  34.     {  
  35.         URL url = new URL(path);  
  36.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  37.         conn.setRequestMethod("GET");  
  38.         conn.setConnectTimeout(5 * 1000);  
  39.         //获取要下载的文件的长度   
  40.         int filelength = conn.getContentLength();  
  41.         //从路径中获取文件名称   
  42.         String filename = getFilename(path);  
  43.         File saveFile = new File(filename);  
  44.         RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");  
  45.         //设置本地文件的长度和下载文件相同   
  46.         accessFile.setLength(filelength);  
  47.         accessFile.close();  
  48.         //计算每条线程下载的数据长度   
  49.         int block = filelength%threadsize==0? filelength/threadsize : filelength/threadsize+1;  
  50.         for(int threadid=0 ; threadid < threadsize ; threadid++){  
  51.             new DownloadThread(url, saveFile, block, threadid).start();  
  52.         }  
  53.     }  
  54.       
  55.     private final class DownloadThread extends Thread  
  56.     {  
  57.         private URL url;  
  58.         private File saveFile;  
  59.         private int block;//每条线程下载的数据长度   
  60.         private int threadid;//线程id   
  61.         public DownloadThread(URL url, File saveFile, int block, int threadid)   
  62.         {  
  63.             this.url = url;  
  64.             this.saveFile = saveFile;  
  65.             this.block = block;  
  66.             this.threadid = threadid;  
  67.         }  
  68.         @Override  
  69.         public void run()   
  70.         {  
  71.             //计算开始位置公式:线程id*每条线程下载的数据长度= ?   
  72.             //计算结束位置公式:(线程id +1)*每条线程下载的数据长度-1 =?   
  73.             int startposition = threadid * block;  
  74.             int endposition = (threadid + 1 ) * block - 1;  
  75.             try   
  76.             {  
  77.                 RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");  
  78.                 //设置从什么位置开始写入数据   
  79.                 accessFile.seek(startposition);  
  80.                 HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  81.                 conn.setRequestMethod("GET");  
  82.                 conn.setConnectTimeout(5 * 1000);  
  83.                 conn.setRequestProperty("Range""bytes="+ startposition+ "-"+ endposition);  
  84.                 InputStream inStream = conn.getInputStream();  
  85.                 byte[] buffer = new byte[1024];  
  86.                 int len = 0;  
  87.                 while( (len=inStream.read(buffer)) != -1 )  
  88.                 {  
  89.                     accessFile.write(buffer, 0, len);  
  90.                 }  
  91.                 inStream.close();  
  92.                 accessFile.close();  
  93.                 System.out.println("线程id:"+ threadid+ "下载完成");  
  94.             }  
  95.             catch (Exception e)   
  96.             {  
  97.                 e.printStackTrace();  
  98.             }  
  99.         }         
  100.     }  
  101. }  

2.多线程断点下载功能,这里把断点数据保存到数据库中:注意代码注释的理解

(0)主Activity,关键点使用Handler更新进度条与开启线程下载避免ANR

若不使用Handler却要立即更新进度条数据,可使用:

//resultView.invalidate(); UI线程中立即更新进度条方法

//resultView.postInvalidate(); 非UI线程中立即更新进度条方法

 

 

  1. /** 
  2.  * 注意这里的设计思路,UI线程与参数保存问题,避免ANR问题,UI控件的显示 
  3.  * @author kay 
  4.  * 
  5.  */  
  6. public class DownloadActivity extends Activity   
  7. {  
  8.     private EditText downloadpathText;  
  9.     private TextView resultView;  
  10.     private ProgressBar progressBar;  
  11.       
  12.     @Override  
  13.     public void onCreate(Bundle savedInstanceState)   
  14.     {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.main);  
  17.           
  18.         downloadpathText = (EditText) this.findViewById(R.id.downloadpath);  
  19.         progressBar = (ProgressBar) this.findViewById(R.id.downloadbar);  
  20.         resultView = (TextView) this.findViewById(R.id.result);  
  21.         Button button = (Button) this.findViewById(R.id.button);  
  22.         button.setOnClickListener(new View.OnClickListener()   
  23.         {             
  24.             @Override  
  25.             public void onClick(View v)   
  26.             {  
  27.                 //取得下载路径   
  28.                 String path = downloadpathText.getText().toString();  
  29.                 //判断SDCard是否存在   
  30.                 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))  
  31.                 {  
  32.                     //下载操作   
  33.                     download(path, Environment.getExternalStorageDirectory());  
  34.                 }  
  35.                 else  
  36.                 {  
  37.                     Toast.makeText(DownloadActivity.this, R.string.sdcarderror, 1).show();  
  38.                 }                 
  39.             }  
  40.         });  
  41.     }  
  42.     //主线程(UI线程)   
  43.     //业务逻辑正确,但是该程序运行的时候有问题(可能出现ANR问题)   
  44.     //对于显示控件的界面更新只是由UI线程负责,如果是在非UI线程更新控件的属性值,更新后的显示界面不会反映到屏幕上   
  45.     /** 
  46.      * 参数类型:因为启动一个线程还需要使用到上面方法的参数,而主方法启动后很快就会销毁, 
  47.      * 那么使用Final可以解决参数丢失的问题 
  48.      * path 注意是Final类型 
  49.      * savedir 注意是Final类型 
  50.      */  
  51.     private void download(final String path, final File savedir)  
  52.     {  
  53.         //这里开启一个线程避免ANR错误   
  54.         new Thread(new Runnable()   
  55.         {             
  56.             @Override  
  57.             public void run()   
  58.             {  
  59.                 FileDownloader loader = new FileDownloader(DownloadActivity.this, path, savedir, 3);  
  60.                 //设置进度条的最大刻度为文件的长度   
  61.                 progressBar.setMax(loader.getFileSize());  
  62.                 try   
  63.                 {  
  64.                     loader.download(new DownloadProgressListener()   
  65.                     {  
  66.                         /** 
  67.                          * 注意这里的设计,显示进度条数据需要使用Handler来处理 
  68.                          * 因为非UI线程更新后的数据不能被刷新 
  69.                          */  
  70.                         @Override  
  71.                         public void onDownloadSize(int size)   
  72.                         {  
  73.                             //实时获知文件已经下载的数据长度   
  74.                             Message msg = new Message();  
  75.                             //设置消息标签   
  76.                             msg.what = 1;  
  77.                             msg.getData().putInt("size", size);  
  78.                             //使用Handler对象发送消息   
  79.                             handler.sendMessage(msg);  
  80.                         }  
  81.                     });  
  82.                 }  
  83.                 catch (Exception e)  
  84.                 {  
  85.                     //发送一个空消息到消息队列   
  86.                     handler.obtainMessage(-1).sendToTarget();  
  87.                     /** 
  88.                      *  或者使用下面的方法发送一个空消息 
  89.                      *  Message msg = new Message(); 
  90.                      *  msg.what = 1; 
  91.                      *  handler.sendMessage(msg); 
  92.                      */                   
  93.                 }  
  94.             }  
  95.         }).start();  
  96.     }  
  97.       
  98.       
  99.     /**Handler原理:当Handler被创建时会关联到创建它的当前线程的消息队列,该类用于往消息队列发送消息 
  100.      *  
  101.      * 消息队列中的消息由当前线程内部进行处理 
  102.      */  
  103.     private Handler handler = new Handler()  
  104.     {  
  105.         //重写Handler里面的handleMessage方法处理消息   
  106.         @Override  
  107.         public void handleMessage(Message msg)   
  108.         {             
  109.             switch (msg.what)   
  110.             {  
  111.                 case 1:  
  112.                     //进度条显示   
  113.                     progressBar.setProgress(msg.getData().getInt("size"));  
  114.                     float num = (float)progressBar.getProgress()/(float)progressBar.getMax();  
  115.                     int result = (int)(num*100);  
  116.                     //resultView.invalidate(); UI线程中立即更新进度条方法   
  117.                     //resultView.postInvalidate(); 非UI线程中立即更新进度条方法   
  118.                     resultView.setText(result+ "%");  
  119.                     //判断是否下载成功   
  120.                     if(progressBar.getProgress()==progressBar.getMax())  
  121.                     {  
  122.                         Toast.makeText(DownloadActivity.this, R.string.success, 1).show();  
  123.                     }  
  124.                     break;    
  125.                 case -1:  
  126.                     Toast.makeText(DownloadActivity.this, R.string.error, 1).show();  
  127.                     break;  
  128.             }  
  129.         }  
  130.     };  
  131.       
  132. }  

 

(1)下载类:

注意计算每条线程的下载长度与下载起始位置的方法

 

 

  1. public class DownloadThread extends Thread   
  2. {  
  3.     private static final String TAG = "DownloadThread";  
  4.     private File saveFile;  
  5.     private URL downUrl;  
  6.     private int block;  
  7.     //下载开始位置   
  8.     private int threadId = -1;    
  9.     //下载文件长度   
  10.     private int downLength;  
  11.     private boolean finish = false;  
  12.     private FileDownloader downloader;  
  13.     public DownloadThread(FileDownloader downloader, URL downUrl, File saveFile, int block, int downLength, int threadId)  
  14.     {  
  15.         this.downUrl = downUrl;  
  16.         this.saveFile = saveFile;  
  17.         this.block = block;  
  18.         this.downloader = downloader;  
  19.         this.threadId = threadId;  
  20.         this.downLength = downLength;  
  21.     }  
  22.       
  23.     @Override  
  24.     public void run()   
  25.     {  
  26.         //未下载完成   
  27.         if(downLength < block)  
  28.         {  
  29.             try  
  30.             {  
  31.                 HttpURLConnection http = (HttpURLConnection) downUrl.openConnection();  
  32.                 http.setConnectTimeout(5 * 1000);  
  33.                 http.setRequestMethod("GET");  
  34.                 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, */*");  
  35.                 http.setRequestProperty("Accept-Language""zh-CN");  
  36.                 http.setRequestProperty("Referer", downUrl.toString());   
  37.                 http.setRequestProperty("Charset""UTF-8");  
  38.                 //下载开始位置:线程id*每条线程下载的数据长度 = ?   
  39.                 int startPos = block * (threadId - 1) + downLength;  
  40.                 //下载结束位置:(线程id+1)*每条线程下载的数据长度-1=?   
  41.                 int endPos = block * threadId -1;  
  42.                 //设置获取实体数据的范围   
  43.                 http.setRequestProperty("Range""bytes=" + startPos + "-"+ endPos);  
  44.                 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)");  
  45.                 http.setRequestProperty("Connection""Keep-Alive");  
  46.                   
  47.                 InputStream inStream = http.getInputStream();  
  48.                 byte[] buffer = new byte[1024];  
  49.                 int offset = 0;  
  50.                 print("Thread " + this.threadId + " start download from position "+ startPos);  
  51.                 RandomAccessFile threadfile = new RandomAccessFile(this.saveFile, "rwd");  
  52.                 threadfile.seek(startPos);  
  53.                 while ((offset = inStream.read(buffer, 01024)) != -1)   
  54.                 {  
  55.                     threadfile.write(buffer, 0, offset);  
  56.                     downLength += offset;  
  57.                     downloader.update(this.threadId, downLength);  
  58.                     downloader.append(offset);  
  59.                 }  
  60.                 threadfile.close();  
  61.                 inStream.close();  
  62.                 print("Thread " + this.threadId + " download finish");  
  63.                 //标记是否完成   
  64.                 this.finish = true;  
  65.             }  
  66.             catch (Exception e)   
  67.             {  
  68.                 this.downLength = -1;  
  69.                 print("Thread "this.threadId+ ":"+ e);  
  70.             }  
  71.         }  
  72.     }  
  73.       
  74.     private static void print(String msg)  
  75.     {  
  76.         Log.i(TAG, msg);  
  77.     }  
  78.       
  79.     /**  
  80.      * 下载是否完成  
  81.      * @return  
  82.      */  
  83.     public boolean isFinish()   
  84.     {  
  85.         return finish;  
  86.     }  
  87.       
  88.     /** 
  89.      * 已经下载的内容大小 
  90.      * @return 如果返回值为-1,代表下载失败 
  91.      */  
  92.     public long getDownLength()   
  93.     {  
  94.         return downLength;  
  95.     }  

 

 

 

 

文件下载器,使用

 

 

 

  1. /** 
  2.  * 文件下载器,使用这个类的方法如下示例: 
  3.  * FileDownloader loader = new FileDownloader(context, "http://browse.babasport.com/ejb3/ActivePort.exe", 
  4.  *              new File("D://androidsoft//test"), 2); 
  5.  *      loader.getFileSize();//得到文件总大小 
  6.  *      try { 
  7.  *          loader.download(new DownloadProgressListener(){ 
  8.  *              public void onDownloadSize(int size) { 
  9.  *                  print("已经下载:"+ size); 
  10.  *              }            
  11.  *          }); 
  12.  *      } 
  13.  *       catch (Exception e)  
  14.  *      { 
  15.  *          e.printStackTrace(); 
  16.  *      } 
  17.  */  
  18. public class FileDownloader   
  19. {  
  20.     private static final String TAG = "FileDownloader";  
  21.     private Context context;  
  22.     private FileService fileService;      
  23.     //已下载文件长度   
  24.     private int downloadSize = 0;  
  25.     //原始文件长度   
  26.     private int fileSize = 0;  
  27.     ///线程数   
  28.     private DownloadThread[] threads;  
  29.     //本地保存文件   
  30.     private File saveFile;  
  31.     //缓存各线程下载的长度   
  32.     private Map<Integer, Integer> data = new ConcurrentHashMap<Integer, Integer>();  
  33.     //每条线程下载的长度   
  34.     private int block;  
  35.     //下载路径   
  36.     private String downloadUrl;  
  37.     //获取线程数   
  38.     public int getThreadSize()   
  39.     {  
  40.         return threads.length;  
  41.     }  
  42.     /** 
  43.      * 获取文件大小 
  44.      * @return 
  45.      */  
  46.     public int getFileSize()   
  47.     {  
  48.         return fileSize;  
  49.     }  
  50.     /** 
  51.      * 累计已下载大小 
  52.      * @param size 
  53.      */  
  54.     protected synchronized void append(int size)   
  55.     {  
  56.         downloadSize += size;  
  57.     }  
  58.     /** 
  59.      * 更新指定线程最后下载的位置 
  60.      * @param threadId 线程id 
  61.      * @param pos 最后下载的位置 
  62.      */  
  63.     protected synchronized void update(int threadId, int pos)   
  64.     {  
  65.         this.data.put(threadId, pos);  
  66.         this.fileService.update(this.downloadUrl, this.data);  
  67.     }  
  68.     /** 
  69.      * 文件下载构造器 
  70.      * @param downloadUrl 下载路径 
  71.      * @param fileSaveDir 文件保存目录 
  72.      * @param threadNum 下载线程数 
  73.      */  
  74.     public FileDownloader(Context context, String downloadUrl, File fileSaveDir, int threadNum)   
  75.     {  
  76.         try   
  77.         {  
  78.             this.context = context;  
  79.             this.downloadUrl = downloadUrl;  
  80.             fileService = new FileService(this.context);  
  81.             URL url = new URL(this.downloadUrl);  
  82.             if(!fileSaveDir.exists()) fileSaveDir.mkdirs();  
  83.             this.threads = new DownloadThread[threadNum];                     
  84.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  85.             conn.setConnectTimeout(5*1000);  
  86.             conn.setRequestMethod("GET");  
  87.             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, */*");  
  88.             conn.setRequestProperty("Accept-Language""zh-CN");  
  89.             conn.setRequestProperty("Referer", downloadUrl);   
  90.             conn.setRequestProperty("Charset""UTF-8");  
  91.             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)");  
  92.             conn.setRequestProperty("Connection""Keep-Alive");  
  93.             conn.connect();  
  94.             printResponseHeader(conn);  
  95.             if (conn.getResponseCode()==200)   
  96.             {  
  97.                 //根据响应获取文件大小   
  98.                 this.fileSize = conn.getContentLength();  
  99.                 if (this.fileSize <= 0throw new RuntimeException("Unkown file size ");  
  100.                 //获取文件名称           
  101.                 String filename = getFileName(conn);  
  102.                 //构建保存文件   
  103.                 this.saveFile = new File(fileSaveDir, filename);  
  104.                 //获取下载记录   
  105.                 Map<Integer, Integer> logdata = fileService.getData(downloadUrl);  
  106.                 //如果存在下载记录   
  107.                 if(logdata.size()>0)  
  108.                 {  
  109.                     //把各条线程已经下载的数据长度放入data中   
  110.                     for(Map.Entry<Integer, Integer> entry : logdata.entrySet())  
  111.                         data.put(entry.getKey(), entry.getValue());  
  112.                 }  
  113.                 //下面计算所有线程已经下载的数据长度   
  114.                 if(this.data.size()==this.threads.length)  
  115.                 {  
  116.                     for (int i = 0; i < this.threads.length; i++)   
  117.                     {  
  118.                         this.downloadSize += this.data.get(i+1);  
  119.                     }  
  120.                     print("已经下载的长度"this.downloadSize);  
  121.                 }  
  122.                 //计算每条线程下载的数据长度   
  123.                 this.block = (this.fileSize % this.threads.length)==0this.fileSize / this.threads.length : this.fileSize / this.threads.length + 1;  
  124.             }  
  125.             else  
  126.             {  
  127.                 throw new RuntimeException("server no response ");  
  128.             }  
  129.         }  
  130.         catch (Exception e)   
  131.         {  
  132.             print(e.toString());  
  133.             throw new RuntimeException("don't connection this url");  
  134.         }  
  135.     }  
  136.     /**  
  137.      * 获取文件名  
  138.      */  
  139.     private String getFileName(HttpURLConnection conn)   
  140.     {  
  141.         String filename = this.downloadUrl.substring(this.downloadUrl.lastIndexOf('/') + 1);  
  142.         if(filename==null || "".equals(filename.trim())){//如果获取不到文件名称   
  143.             for (int i = 0;; i++) {  
  144.                 String mine = conn.getHeaderField(i);  
  145.                 if (mine == nullbreak;  
  146.                 if("content-disposition".equals(conn.getHeaderFieldKey(i).toLowerCase())){  
  147.                     Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());  
  148.                     if(m.find()) return m.group(1);  
  149.                 }  
  150.             }  
  151.             filename = UUID.randomUUID()+ ".tmp";//默认取一个文件名   
  152.         }  
  153.         return filename;  
  154.     }  
  155.       
  156.     /** 
  157.      *  开始下载文件 
  158.      * @param listener 监听下载数量的变化,如果不需要了解实时下载的数量,可以设置为null 
  159.      * @return 已下载文件大小 
  160.      * @throws Exception 
  161.      */  
  162.     public int download(DownloadProgressListener listener) throws Exception{  
  163.         try   
  164.         {  
  165.             //创建本地文件   
  166.             RandomAccessFile randOut = new RandomAccessFile(this.saveFile, "rw");  
  167.             if(this.fileSize>0) randOut.setLength(this.fileSize);  
  168.             randOut.close();  
  169.             URL url = new URL(this.downloadUrl);  
  170.             if(this.data.size() != this.threads.length)  
  171.             {  
  172.                 this.data.clear();  
  173.                 for (int i = 0; i < this.threads.length; i++)   
  174.                 {  
  175.                     //初始化每条线程已经下载的数据长度为0   
  176.                     this.data.put(i+10);  
  177.                 }  
  178.             }  
  179.             //开启线程进行下载   
  180.             for (int i = 0; i < this.threads.length; i++)   
  181.             {  
  182.                 int downLength = this.data.get(i+1);  
  183.                 //判断线程是否已经完成下载,否则继续下载   
  184.                 if(downLength < this.block && this.downloadSize<this.fileSize)  
  185.                 {     
  186.                     this.threads[i] = new DownloadThread(this, url, this.saveFile, this.block, this.data.get(i+1), i+1);  
  187.                     this.threads[i].setPriority(7);//可删除这条   
  188.                     this.threads[i].start();  
  189.                 }  
  190.                 else  
  191.                 {  
  192.                     this.threads[i] = null;  
  193.                 }  
  194.             }  
  195.             this.fileService.save(this.downloadUrl, this.data);  
  196.             //下载未完成   
  197.             boolean notFinish = true;  
  198.             // 循环判断所有线程是否完成下载   
  199.             while (notFinish)   
  200.             {  
  201.                 Thread.sleep(900);  
  202.                 //假定全部线程下载完成   
  203.                 notFinish = false;  
  204.                 for (int i = 0; i < this.threads.length; i++)  
  205.                 {  
  206.                     //如果发现线程未完成下载   
  207.                     if (this.threads[i] != null && !this.threads[i].isFinish())   
  208.                     {  
  209.                         //设置标志为下载没有完成   
  210.                         notFinish = true;  
  211.                         //如果下载失败,再重新下载   
  212.                         if(this.threads[i].getDownLength() == -1)  
  213.                         {  
  214.                             this.threads[i] = new DownloadThread(this, url, this.saveFile, this.block, this.data.get(i+1), i+1);  
  215.                             this.threads[i].setPriority(7);  
  216.                             this.threads[i].start();  
  217.                         }  
  218.                     }  
  219.                 }  
  220.                 //通知目前已经下载完成的数据长度   
  221.                 if(listener!=null) listener.onDownloadSize(this.downloadSize);  
  222.             }  
  223.             //删除数据库中下载信息   
  224.             fileService.delete(this.downloadUrl);  
  225.         }  
  226.         catch (Exception e)   
  227.         {  
  228.             print(e.toString());  
  229.             throw new Exception("file download fail");  
  230.         }  
  231.         return this.downloadSize;  
  232.     }  
  233.       
  234.     /** 
  235.      * 获取Http响应头字段 
  236.      * @param http 
  237.      * @return 
  238.      */  
  239.     public static Map<String, String> getHttpResponseHeader(HttpURLConnection http) {  
  240.         Map<String, String> header = new LinkedHashMap<String, String>();  
  241.         for (int i = 0;; i++) {  
  242.             String mine = http.getHeaderField(i);  
  243.             if (mine == nullbreak;  
  244.             header.put(http.getHeaderFieldKey(i), mine);  
  245.         }  
  246.         return header;  
  247.     }  
  248.     /** 
  249.      * 打印Http头字段 
  250.      * @param http 
  251.      */  
  252.     public static void printResponseHeader(HttpURLConnection http)  
  253.     {  
  254.         Map<String, String> header = getHttpResponseHeader(http);  
  255.         for(Map.Entry<String, String> entry : header.entrySet())  
  256.         {  
  257.             String key = entry.getKey()!=null ? entry.getKey()+ ":" : "";  
  258.             print(key+ entry.getValue());  
  259.         }  
  260.     }  
  1. public interface DownloadProgressListener   
  2. {  
  3.     public void onDownloadSize(int size);  
  4. }  

 

 

(2)文件操作,断点数据库存储

 

 

 

  1. public class DBOpenHelper extends SQLiteOpenHelper   
  2. {  
  3.     private static final String DBNAME = "itcast.db";  
  4.     private static final int VERSION = 1;  
  5.       
  6.     public DBOpenHelper(Context context)   
  7.     {  
  8.         super(context, DBNAME, null, VERSION);  
  9.     }  
  10.       
  11.     @Override  
  12.     public void onCreate(SQLiteDatabase db)   
  13.     {  
  14.         db.execSQL("CREATE TABLE IF NOT EXISTS filedownlog (id integer primary key autoincrement, downpath varchar(100), threadid INTEGER, downlength INTEGER)");  
  15.     }  
  16.     @Override  
  17.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)   
  18.     {  
  19.         db.execSQL("DROP TABLE IF EXISTS filedownlog");  
  20.         onCreate(db);  
  21.     }  
  22. }  

 

 

  1. ** 
  2.  * 文件下载业务bean 
  3.  */  
  4. public class FileService   
  5. {  
  6.     private DBOpenHelper openHelper;  
  7.     public FileService(Context context)   
  8.     {  
  9.         openHelper = new DBOpenHelper(context);  
  10.     }  
  11.     /** 
  12.      * 获取每条线程已经下载的文件长度 
  13.      * @param path 
  14.      * @return 
  15.      */  
  16.     public Map<Integer, Integer> getData(String path)  
  17.     {  
  18.         SQLiteDatabase db = openHelper.getReadableDatabase();  
  19.         Cursor cursor = db.rawQuery("select threadid, downlength from filedownlog where downpath=?"new String[]{path});  
  20.         Map<Integer, Integer> data = new HashMap<Integer, Integer>();  
  21.         while(cursor.moveToNext())  
  22.         {  
  23.             data.put(cursor.getInt(0), cursor.getInt(1));  
  24.         }  
  25.         cursor.close();  
  26.         db.close();  
  27.         return data;  
  28.     }  
  29.     /** 
  30.      * 保存每条线程已经下载的文件长度 
  31.      * @param path 
  32.      * @param map 
  33.      */  
  34.     public void save(String path,  Map<Integer, Integer> map)  
  35.     {//int threadid, int position   
  36.         SQLiteDatabase db = openHelper.getWritableDatabase();  
  37.         db.beginTransaction();  
  38.         try  
  39.         {  
  40.             for(Map.Entry<Integer, Integer> entry : map.entrySet())  
  41.             {  
  42.                 db.execSQL("insert into filedownlog(downpath, threadid, downlength) values(?,?,?)",  
  43.                         new Object[]{path, entry.getKey(), entry.getValue()});  
  44.             }  
  45.             db.setTransactionSuccessful();  
  46.         }  
  47.         finally  
  48.         {  
  49.             db.endTransaction();  
  50.         }  
  51.         db.close();  
  52.     }  
  53.     /** 
  54.      * 实时更新每条线程已经下载的文件长度 
  55.      * @param path 
  56.      * @param map 
  57.      */  
  58.     public void update(String path, Map<Integer, Integer> map)  
  59.     {  
  60.         SQLiteDatabase db = openHelper.getWritableDatabase();  
  61.         db.beginTransaction();  
  62.         try{  
  63.             for(Map.Entry<Integer, Integer> entry : map.entrySet()){  
  64.                 db.execSQL("update filedownlog set downlength=? where downpath=? and threadid=?",  
  65.                         new Object[]{entry.getValue(), path, entry.getKey()});  
  66.             }  
  67.             db.setTransactionSuccessful();  
  68.         }finally{  
  69.             db.endTransaction();  
  70.         }  
  71.         db.close();  
  72.     }  
  73.     /** 
  74.      * 当文件下载完成后,删除对应的下载记录 
  75.      * @param path 
  76.      */  
  77.     public void delete(String path)  
  78.     {  
  79.         SQLiteDatabase db = openHelper.getWritableDatabase();  
  80.         db.execSQL("delete from filedownlog where downpath=?"new Object[]{path});  
  81.         db.close();  
  82.     }     
  83. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics