你好,游客 登录 注册 搜索
背景:
阅读新闻

Android实现多任务多线程支持断点续传的下载软件

[日期:2011-10-10] 来源:Linux社区  作者:badboy1110 [字体:大 中 小]

四、下载器类,为MainActivity提供服务(方法)

  1. package com.song.service;  
  2.   
  3. import java.io.File;  
  4. import java.io.InputStream;  
  5. import java.io.RandomAccessFile;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.URL;  
  8. import java.util.ArrayList;  
  9. import java.util.List;  
  10.   
  11. import Android.content.Context;  
  12. import android.os.Handler;  
  13. import android.os.Message;  
  14. import android.util.Log;  
  15.   
  16. import com.song.dao.DownloadDao;  
  17. import com.song.entity.DownloadInfo;  
  18. import com.song.entity.ThreadDownloadInfo;  
  19.   
  20. /** 
  21.  * 下载服务类 
  22.  *  
  23.  * @author song 
  24.  *  
  25.  */  
  26. public class DownLoader  
  27. {  
  28.     private String urlString;// 下载地址   
  29.     private String localFile;// 保存的文件   
  30.     private int threadCount;// 开启的线程数   
  31.     private int fileSize;// 文件大小   
  32.     private Handler mHandler;// 同步进度条   
  33.     private DownloadDao dao;// 数据库操作类   
  34.     private List<ThreadDownloadInfo> infos;// 保存下载信息   
  35.   
  36.     // 标记下载状态   
  37.     public static final int INIT = 1; // 初始状态   
  38.     public static final int DOWNLOADING = 2;// 正在下载   
  39.     public static final int PAUSE = 3;// 暂停   
  40.     private int state = INIT;  
  41.   
  42.     public DownLoader(String urlString, String localFile, int threadCount,  
  43.             Context context, Handler handler)  
  44.     {  
  45.         this.urlString = urlString;  
  46.         this.localFile = localFile;  
  47.         this.threadCount = threadCount;  
  48.         mHandler = handler;  
  49.         dao = new DownloadDao(context);  
  50.     }  
  51.   
  52.     /** 
  53.      * 下载 
  54.      */  
  55.     public void download()  
  56.     {  
  57.         if (infos != null)  
  58.         {  
  59.             Log.v("TAG", "download()------->infos != null");  
  60.             if (state == DOWNLOADING)  
  61.             {  
  62.                 return;  
  63.             }  
  64.             state = DOWNLOADING;  
  65.             for (ThreadDownloadInfo info : infos)  
  66.             {  
  67.                 new DownloadThread(info.getThreadId(), info.getStartPos(),  
  68.                         info.getEndPos(), info.getCompleteSize(),info.getUrlString()).start();  
  69.             }  
  70.         }  
  71.     }  
  72.   
  73.     /** 
  74.      * 下载器是否正在下载 true: 正在下载 
  75.      */  
  76.     public boolean isDownloading()  
  77.     {  
  78.         return state == DOWNLOADING;  
  79.     }  
  80.   
  81.     /** 
  82.      * 得到当前下载信息 
  83.      *  
  84.      * @return 
  85.      */  
  86.     public DownloadInfo getDownloadInfo()  
  87.     {  
  88.         if (isFirst(urlString))  
  89.         {  
  90.             init();  
  91.             infos = new ArrayList<ThreadDownloadInfo>();  
  92.             int range = fileSize / threadCount;  
  93.             for (int i = 0; i < threadCount - 1; i++)  
  94.             {  
  95.                 ThreadDownloadInfo info = new ThreadDownloadInfo(i, i * range,  
  96.                         (i + 1) * range - 1, 0, urlString);  
  97.                 infos.add(info);  
  98.             }  
  99.             ThreadDownloadInfo info = new ThreadDownloadInfo(threadCount - 1,  
  100.                     (threadCount - 1) * range, fileSize - 1, 0, urlString);  
  101.             infos.add(info);  
  102.             dao.saveInfos(infos);  
  103.             return new DownloadInfo(fileSize, 0, urlString);  
  104.         } else  
  105.         {  
  106.             infos = dao.getInfos(urlString);  
  107.             int size = 0;  
  108.             int completeSize = 0;  
  109.             for (ThreadDownloadInfo info : infos)  
  110.             {  
  111.                 completeSize += info.getCompleteSize();  
  112.                 size += info.getEndPos() - info.getStartPos() + 1;  
  113.             }  
  114.             return new DownloadInfo(size, completeSize, urlString);  
  115.         }  
  116.     }  
  117.   
  118.     /** 
  119.      * 初始化 连接网络,准备文件的保存路径等 
  120.      */  
  121.     private void init()  
  122.     {  
  123.         try  
  124.         {  
  125.             URL url = new URL(urlString);  
  126.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  127.             conn.setRequestMethod("GET");  
  128.             conn.setConnectTimeout(5000);  
  129.   
  130.             fileSize = conn.getContentLength();  
  131.             File file = new File(localFile);  
  132.             if (file.exists())  
  133.             {  
  134.                 file.delete();  
  135.             }   
  136.             file.createNewFile();  
  137.               
  138.             RandomAccessFile rFile = new RandomAccessFile(localFile, "rwd");  
  139.             rFile.setLength(fileSize);  
  140.   
  141.             rFile.close();  
  142.             conn.disconnect();  
  143.   
  144.         } catch (Exception e)  
  145.         {  
  146.             e.printStackTrace();  
  147.         }  
  148.     }  
  149.   
  150.     /** 
  151.      * 判断是不是断点续传(即是不是第一次下载) true:第一次下载 
  152.      *  
  153.      * @param urlString 
  154.      * @return 
  155.      */  
  156.     private boolean isFirst(String urlString)  
  157.     {  
  158.         return dao.unhasInfo(urlString);  
  159.     }  
  160.   
  161.     /** 
  162.      * 暂停 
  163.      */  
  164.     public void pause()  
  165.     {  
  166.         state = PAUSE;  
  167.     }  
  168.   
  169.     /** 
  170.      * 下载的线程类 
  171.      *  
  172.      * @author song 
  173.      */  
  174.     private class DownloadThread extends Thread  
  175.     {  
  176.         private int threadId;  
  177.         private int startPos;  
  178.         private int endPos;  
  179.         private int completeSize;  
  180.         private String urlString;  
  181.   
  182.         public DownloadThread(int threadId, int startPos, int endPos,  
  183.                 int completeSize, String urlString)  
  184.         {  
  185.             this.threadId = threadId;  
  186.             this.startPos = startPos;  
  187.             this.endPos = endPos;  
  188.             this.completeSize = completeSize;  
  189.             this.urlString = urlString;  
  190.         }  
  191.   
  192.         @Override  
  193.         public void run()  
  194.         {  
  195.             HttpURLConnection conn = null;  
  196.             RandomAccessFile rFile = null;  
  197.             InputStream is = null;  
  198.               
  199.             try  
  200.             {  
  201.                 URL url = new URL(urlString);  
  202.                 conn = (HttpURLConnection) url.openConnection();  
  203.                 conn.setRequestMethod("GET");  
  204.                 conn.setConnectTimeout(4000);  
  205.                 conn.setRequestProperty("Range", "bytes="  
  206.                         + (startPos + completeSize) + "-" + endPos);  
  207.   
  208.                 rFile = new RandomAccessFile(localFile, "rwd");  
  209.                 rFile.seek(startPos + completeSize);  
  210.   
  211.                 is = conn.getInputStream();  
  212.                 byte[] buffer = new byte[2048];  
  213.                 int len = -1;  
  214.                 while ((len = is.read(buffer)) != -1)  
  215.                 {  
  216.                     rFile.write(buffer, 0, len);  
  217.                     completeSize += len;  
  218.                     dao.updateInfo(threadId, completeSize, urlString);  
  219.                     Message msg = Message.obtain();  
  220.                     msg.what = 1;  
  221.                     msg.arg2 = len;  
  222.                     msg.obj = urlString;  
  223.                     mHandler.sendMessage(msg);  
  224.                     Log.v("TAG", "completeSize="+completeSize);  
  225.                     if (state == PAUSE)  
  226.                     {  
  227.                         return;  
  228.                     }  
  229.                 }  
  230.             } catch (Exception e)  
  231.             {  
  232.                 e.printStackTrace();  
  233.             } finally  
  234.             {  
  235.                 try  
  236.                 {  
  237.                     is.close();  
  238.                     rFile.close();  
  239.                     conn.disconnect();  
  240.                     dao.closeDB();  
  241.                 } catch (Exception e)  
  242.                 {  
  243.                     e.printStackTrace();  
  244.                 }  
  245.             }  
  246.         }  
  247.     }  
  248.   
  249.     public void deleteInfo(String urlString)  
  250.     {  
  251.         dao.deleteInfos(urlString);  
  252.     }  
  253.       
  254.     public void closeDB() {  
  255.         dao.closeDB();  
  256.     }  
  257. }  

PS:这个写的很简单,实现了最基本的功能。后续可以加上服务,实现后台下载。

linux
相关资讯       Android开发 
本文评论   查看全部评论 (1)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款
第 1 楼
* lala 发表于 2012/3/8 11:10:59
缺个xml文件