现在的位置: 首页 > 综合 > 正文

Android网络多线程断点续传下载

2017年10月14日 ⁄ 综合 ⁄ 共 20609字 ⁄ 字号 评论关闭

本示例介绍在Android平台下通过HTTP协议实现断点续传下载。

        我们编写的是Andorid的HTTP协议多线程断点下载应用程序。直接使用单线程下载HTTP文件对我们来说是一件非常简单的事。那么,多线程断点需要什么功能?难在哪里?

        1.多线程下载,

        2.支持断点。

       
使用多线程的好处:使用多线程下载会提升文件下载的速度。那么多线程下载文件的过程是:

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

             HttpURLConnection.getContentLength();//获取下载文件的长度

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

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

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

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

           1.gif

2012-3-4 11:02 上传

下载附件
(10.2 KB)

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

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

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

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

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

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

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

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

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

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

          程序结构如下图所示:

          2.jpg

2012-3-4 11:02 上传

下载附件
(123.9 KB)

         string.xml文件中代码:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3.     <string name="hello">Hello World, MainActivity!</string>
  4.     <string name="app_name">Android网络多线程断点下载</string>
  5.     <string name="path">下载路径</string>
  6.     <string name="downloadbutton">下载</string>
  7.     <string name="sdcarderror">SDCard不存在或者写保护</string>
  8.     <string name="success">下载完成</string>
  9.     <string name="error">下载失败</string>
  10. </resources>

复制代码

main.xml文件中代码:

  1. <?xml version="1.0" encoding="utf-8"?>   
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"   
  4. android:layout_width="fill_parent"   
  5. android:layout_height="fill_parent">
  6.     <!-- 下载路径 -->
  7.     <TextView
  8.         android:layout_width="fill_parent"
  9.         android:layout_height="wrap_content"
  10.         android:text="@string/path"/>
  11.     <EditText
  12.         android:id="@+id/path"
  13.         android:text="http://www.winrar.com.cn/download/wrar380sc.exe"
  14.         android:layout_width="fill_parent"
  15.         android:layout_height="wrap_content">
  16.     </EditText>
  17.     <!-- 下载按钮 -->
  18.     <Button
  19.         android:layout_width="wrap_content"
  20.         android:layout_height="wrap_content"
  21.         android:text="@string/downloadbutton"
  22.         android:id="@+id/button"/>
  23.     <!-- 进度条 -->
  24.     <ProgressBar
  25.         android:layout_width="fill_parent"
  26.         android:layout_height="20dip"
  27.         style="?android:attr/progressBarStyleHorizontal"
  28.         android:id="@+id/downloadbar" />
  29.     <TextView
  30.         android:layout_width="fill_parent"
  31.         android:layout_height="wrap_content"
  32.         android:gravity="center"
  33.         android:id="@+id/resultView" />
  34.     </LinearLayout>

复制代码

  AndroidManifest.xml文件中代码:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="com.android.downloader"      android:versionCode="1"      android:versionName="1.0">
  3.     <uses-sdk android:minSdkVersion="8" />
  4.     <application android:icon="@drawable/icon" android:label="@string/app_name">
  5.         <activity android:name=".MainActivity"
  6.                   android:label="@string/app_name">
  7.             <intent-filter>
  8.                 <action android:name="android.intent.action.MAIN" />
  9.                 <category android:name="android.intent.category.LAUNCHER" />
  10.             </intent-filter>
  11.         </activity>
  12.     </application>
  13.    
  14.     <!-- 在SDCard中创建与删除文件权限 -->
  15.     <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
  16.    
  17.     <!-- 往SDCard写入数据权限 -->
  18.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  19.    
  20.     <!-- 访问internet权限 -->
  21.     <uses-permission android:name="android.permission.INTERNET"/>
  22. </manifest>  

复制代码

MainActivity中代码:

  1. package com.android.downloader;
  2. import java.io.File;
  3. import com.android.network.DownloadProgressListener;
  4. import com.android.network.FileDownloader;
  5. import android.app.Activity;
  6. import android.os.Bundle;
  7. import android.os.Environment;
  8. import android.os.Handler;
  9. import android.os.Message;
  10. import android.view.View;
  11. import android.widget.Button;
  12. import android.widget.EditText;
  13. import android.widget.ProgressBar;
  14. import android.widget.TextView;
  15. import android.widget.Toast;
  16. public class MainActivity extends Activity {
  17.     private EditText downloadpathText;
  18.     private TextView resultView;
  19.     private ProgressBar progressBar;
  20.    
  21.     /**
  22.      * 当Handler被创建会关联到创建它的当前线程的消息队列,该类用于往消息队列发送消息
  23.      * 消息队列中的消息由当前线程内部进行处理
  24.      */
  25.     private Handler handler = new Handler(){
  26.         @Override
  27.         public void handleMessage(Message msg) {            
  28.             switch (msg.what) {
  29.             case 1:               
  30.                 progressBar.setProgress(msg.getData().getInt("size"));
  31.                 float num = (float)progressBar.getProgress()/(float)progressBar.getMax();
  32.                 int result = (int)(num*100);
  33.                 resultView.setText(result+ "%");
  34.                
  35.                 if(progressBar.getProgress()==progressBar.getMax()){
  36.                     Toast.makeText(MainActivity.this, R.string.success, 1).show();
  37.                 }
  38.                 break;
  39.             case -1:
  40.                 Toast.makeText(MainActivity.this, R.string.error, 1).show();
  41.                 break;
  42.             }
  43.         }
  44.     };
  45.    
  46.     /** Called when the activity is first created. */
  47.     @Override
  48.     public void onCreate(Bundle savedInstanceState) {
  49.         super.onCreate(savedInstanceState);
  50.         setContentView(R.layout.main);
  51.         
  52.         downloadpathText = (EditText) this.findViewById(R.id.path);
  53.         progressBar = (ProgressBar) this.findViewById(R.id.downloadbar);
  54.         resultView = (TextView) this.findViewById(R.id.resultView);
  55.         Button button = (Button) this.findViewById(R.id.button);
  56.         
  57.         button.setOnClickListener(new View.OnClickListener() {
  58.             
  59.             @Override
  60.             public void onClick(View v) {
  61.                 // TODO Auto-generated method stub
  62.                 String path = downloadpathText.getText().toString();
  63.                 System.out.println(Environment.getExternalStorageState()+"------"+Environment.MEDIA_MOUNTED);
  64.                
  65.                 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
  66.                     download(path, Environment.getExternalStorageDirectory());
  67.                 }else{
  68.                     Toast.makeText(MainActivity.this, R.string.sdcarderror, 1).show();
  69.                 }
  70.             }
  71.         });
  72.     }
  73.    
  74.       /**
  75.        * 主线程(UI线程)
  76.        * 对于显示控件的界面更新只是由UI线程负责,如果是在非UI线程更新控件的属性值,更新后的显示界面不会反映到屏幕上
  77.        * @param path
  78.        * @param savedir
  79.        */
  80.     private void download(final String path, final File savedir) {
  81.         new Thread(new Runnable() {            
  82.             @Override
  83.             public void run() {
  84.                 FileDownloader loader = new FileDownloader(MainActivity.this, path, savedir, 3);
  85.                 progressBar.setMax(loader.getFileSize());//设置进度条的最大刻度为文件的长度
  86.                
  87.                 try {
  88.                     loader.download(new DownloadProgressListener() {
  89.                         @Override
  90.                         public void onDownloadSize(int size) {//实时获知文件已经下载的数据长度
  91.                             Message msg = new Message();
  92.                             msg.what = 1;
  93.                             msg.getData().putInt("size", size);
  94.                             handler.sendMessage(msg);//发送消息
  95.                         }
  96.                     });
  97.                 } catch (Exception e) {
  98.                     handler.obtainMessage(-1).sendToTarget();
  99.                 }
  100.             }
  101.         }).start();
  102.     }
  103. }  

复制代码

DBOpenHelper中代码:

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

复制代码

FileService中代码:

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

复制代码

DownloadProgressListener中代码:

  1. package com.android.network;
  2. public interface DownloadProgressListener {
  3.     public void onDownloadSize(int size);
  4. }  

复制代码

FileDownloader中代码:

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

复制代码

DownloadThread 中代码:

  1. package com.android.network;
  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. public class DownloadThread extends Thread {
  9.     private static final String TAG = "DownloadThread";
  10.     private File saveFile;
  11.     private URL downUrl;
  12.     private int block;
  13.    
  14.     /* 下载开始位置  */
  15.     private int threadId = -1;   
  16.     private int downLength;
  17.     private boolean finish = false;
  18.     private FileDownloader downloader;
  19.    
  20.     public DownloadThread(FileDownloader downloader, URL downUrl, File saveFile, int block, int downLength, int threadId) {
  21.         this.downUrl = downUrl;
  22.         this.saveFile = saveFile;
  23.         this.block = block;
  24.         this.downloader = downloader;
  25.         this.threadId = threadId;
  26.         this.downLength = downLength;
  27.     }
  28.    
  29.     @Override
  30.     public void run() {
  31.         if(downLength < block){//未下载完成
  32.             try {
  33.                 HttpURLConnection http = (HttpURLConnection) downUrl.openConnection();
  34.                 http.setConnectTimeout(5 * 1000);
  35.                 http.setRequestMethod("GET");
  36.                 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, */*");
  37.                 http.setRequestProperty("Accept-Language", "zh-CN");
  38.                 http.setRequestProperty("Referer", downUrl.toString());
  39.                 http.setRequestProperty("Charset", "UTF-8");
  40.                 int startPos = block * (threadId - 1) + downLength;//开始位置
  41.                 int endPos = block * threadId -1;//结束位置
  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.                
  53.                 while ((offset = inStream.read(buffer, 0, 1024)) != -1) {
  54.                     threadfile.write(buffer, 0, offset);
  55.                     downLength += offset;
  56.                     downloader.update(this.threadId, downLength);
  57.                     downloader.append(offset);
  58.                 }
  59.                
  60.                 threadfile.close();
  61.                 inStream.close();
  62.                 print("Thread " + this.threadId + " download finish");
  63.                 this.finish = true;
  64.             } catch (Exception e) {
  65.                 this.downLength = -1;
  66.                 print("Thread "+ this.threadId+ ":"+ e);
  67.             }
  68.         }
  69.     }
  70.    
  71.     private static void print(String msg){
  72.         Log.i(TAG, msg);
  73.     }
  74.    
  75.     /**
  76.      * 下载是否完成
  77.      * @return
  78.      */
  79.     public boolean isFinish() {
  80.         return finish;
  81.     }
  82.    
  83.     /**
  84.      * 已经下载的内容大小
  85.      * @return 如果返回值为-1,代表下载失败
  86.      */
  87.     public long getDownLength() {
  88.         return downLength;
  89.     }
  90. }

复制代码

运行效果如下:        3.jpg

2012-3-4 11:02 上传

下载附件
(31.19 KB)

          完毕。^_^  

抱歉!评论已关闭.