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

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

(1)下载类:

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

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

文件下载器,使用

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

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

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

  1. **
  2. * 文件下载业务bean
  3. */ 
  4. public class FileService  
  5.     private DBOpenHelper openHelper; 
  6.     public FileService(Context context)  
  7.     { 
  8.         openHelper = new DBOpenHelper(context); 
  9.     } 
  10.     /**
  11.      * 获取每条线程已经下载的文件长度
  12.      * @param path
  13.      * @return
  14.      */ 
  15.     public Map<Integer, Integer> getData(String path) 
  16.     { 
  17.         SQLiteDatabase db = openHelper.getReadableDatabase(); 
  18.         Cursor cursor = db.rawQuery("select threadid, downlength from filedownlog where downpath=?", new String[]{path}); 
  19.         Map<Integer, Integer> data = new HashMap<Integer, Integer>(); 
  20.         while(cursor.moveToNext()) 
  21.         { 
  22.             data.put(cursor.getInt(0), cursor.getInt(1)); 
  23.         } 
  24.         cursor.close(); 
  25.         db.close(); 
  26.         return data; 
  27.     } 
  28.     /**
  29.      * 保存每条线程已经下载的文件长度
  30.      * @param path
  31.      * @param map
  32.      */ 
  33.     public void save(String path,  Map<Integer, Integer> map) 
  34.     {//int threadid, int position  
  35.         SQLiteDatabase db = openHelper.getWritableDatabase(); 
  36.         db.beginTransaction(); 
  37.         try 
  38.         { 
  39.             for(Map.Entry<Integer, Integer> entry : map.entrySet()) 
  40.             { 
  41.                 db.execSQL("insert into filedownlog(downpath, threadid, downlength) values(?,?,?)"
  42.                         new Object[]{path, entry.getKey(), entry.getValue()}); 
  43.             } 
  44.             db.setTransactionSuccessful(); 
  45.         } 
  46.         finally 
  47.         { 
  48.             db.endTransaction(); 
  49.         } 
  50.         db.close(); 
  51.     } 
  52.     /**
  53.      * 实时更新每条线程已经下载的文件长度
  54.      * @param path
  55.      * @param map
  56.      */ 
  57.     public void update(String path, Map<Integer, Integer> map) 
  58.     { 
  59.         SQLiteDatabase db = openHelper.getWritableDatabase(); 
  60.         db.beginTransaction(); 
  61.         try
  62.             for(Map.Entry<Integer, Integer> entry : map.entrySet()){ 
  63.                 db.execSQL("update filedownlog set downlength=? where downpath=? and threadid=?"
  64.                         new Object[]{entry.getValue(), path, entry.getKey()}); 
  65.             } 
  66.             db.setTransactionSuccessful(); 
  67.         }finally
  68.             db.endTransaction(); 
  69.         } 
  70.         db.close(); 
  71.     } 
  72.     /**
  73.      * 当文件下载完成后,删除对应的下载记录
  74.      * @param path
  75.      */ 
  76.     public void delete(String path) 
  77.     { 
  78.         SQLiteDatabase db = openHelper.getWritableDatabase(); 
  79.         db.execSQL("delete from filedownlog where downpath=?", new Object[]{path}); 
  80.         db.close(); 
  81.     }    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在信号处理领域,DOA(Direction of Arrival)估计是一项关键技术,主要用于确定多个信号源到达接收阵列的方向。本文将详细探讨三种ESPRIT(Estimation of Signal Parameters via Rotational Invariance Techniques)算法在DOA估计中的实现,以及它们在MATLAB环境中的具体应用。 ESPRIT算法是由Paul Kailath等人于1986年提出的,其核心思想是利用阵列数据的旋转不变性来估计信号源的角度。这种算法相比传统的 MUSIC(Multiple Signal Classification)算法具有较低的计算复杂度,且无需进行特征值分解,因此在实际应用中颇具优势。 1. 普通ESPRIT算法 普通ESPRIT算法分为两个主要步骤:构造等效旋转不变系统和估计角度。通过空间平移(如延时)构建两个子阵列,使得它们之间的关系具有旋转不变性。然后,通过对子阵列数据进行最小二乘拟合,可以得到信号源的角频率估计,进一步转换为DOA估计。 2. 常规ESPRIT算法实现 在描述中提到的`common_esprit_method1.m`和`common_esprit_method2.m`是两种不同的普通ESPRIT算法实现。它们可能在实现细节上略有差异,比如选择子阵列的方式、参数估计的策略等。MATLAB代码通常会包含预处理步骤(如数据归一化)、子阵列构造、旋转不变性矩阵的建立、最小二乘估计等部分。通过运行这两个文件,可以比较它们在估计精度和计算效率上的异同。 3. TLS_ESPRIT算法 TLS(Total Least Squares)ESPRIT是对普通ESPRIT的优化,它考虑了数据噪声的影响,提高了估计的稳健性。在TLS_ESPRIT算法中,不假设数据噪声是高斯白噪声,而是采用总最小二乘准则来拟合数据。这使得算法在噪声环境下表现更优。`TLS_esprit.m`文件应该包含了TLS_ESPRIT算法的完整实现,包括TLS估计的步骤和旋转不变性矩阵的改进处理。 在实际应用中,选择合适的ESPRIT变体取决于系统条件,例如噪声水平、信号质量以及计算资源。通过MATLAB实现,研究者和工程师可以方便地比较不同算法的效果,并根据需要进行调整和优化。同时,这些代码也为教学和学习DOA估计提供了一个直观的平台,有助于深入理解ESPRIT算法的工作原理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值