Android 多线程断点续传下载 二

来源:互联网 发布:幸运28算法公式 编辑:程序博客网 时间:2024/05/04 01:00

在上一集中,我们简单介绍了如何创建多任务下载,但那种还不能拿来实用,这一集我们重点通过代码为大家展示如何创建多线程断点续传下载,这在实际项目中很常用.

main.xml:

[html] view plaincopy
  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.     <EditText  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:id="@+id/editText"  
  11.         android:text="http://gongxue.cn/yingyinkuaiche/UploadFiles_9323/201008/2010082909434077.mp3"  
  12.     />  
  13.     <LinearLayout  
  14.         android:orientation="horizontal"  
  15.         android:layout_width="match_parent"  
  16.         android:layout_height="wrap_content"  
  17.     >  
  18.         <Button  
  19.             android:layout_width="wrap_content"  
  20.             android:layout_height="wrap_content"  
  21.             android:id="@+id/downButton"  
  22.             android:text="Download"  
  23.         />  
  24.         <Button  
  25.             android:layout_width="wrap_content"  
  26.             android:layout_height="wrap_content"  
  27.             android:id="@+id/pauseButton"  
  28.             android:enabled="false"  
  29.             android:text="Pause"  
  30.         />  
  31.     </LinearLayout>  
  32.       
  33.     <ProgressBar  
  34.         android:layout_width="match_parent"  
  35.         android:layout_height="18dp"  
  36.         style="?android:attr/progressBarStyleHorizontal"  
  37.         android:id="@+id/progressBar"  
  38.     />  
  39.     <TextView  
  40.         android:layout_width="fill_parent"  
  41.         android:layout_height="wrap_content"  
  42.         android:id="@+id/textView"  
  43.         android:gravity="center"  
  44.     />  
  45. </LinearLayout>  

 

String.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="hello">Hello World, Main!</string>  
  4.     <string name="app_name">多线程断点续传下载</string>  
  5. </resources>  


AndroidManifest.xml:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="sms.multithreaddownload"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7.         <activity android:name=".Main"  
  8.                   android:label="@string/app_name">  
  9.             <intent-filter>  
  10.                 <action android:name="android.intent.action.MAIN" />  
  11.                 <category android:name="android.intent.category.LAUNCHER" />  
  12.             </intent-filter>  
  13.         </activity>  
  14.      <uses-library android:name="android.test.runner" />  
  15.     </application>  
  16.     <uses-sdk android:minSdkVersion="8" />  
  17.     <instrumentation  
  18.         android:targetPackage="sms.multithreaddownload"  
  19.         android:name="android.test.InstrumentationTestRunner" />  
  20.     <!-- 访问网络的权限 -->  
  21.     <uses-permission android:name="android.permission.INTERNET"/>  
  22.     <!-- SDCard写数据的权限 -->  
  23.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
  24.       
  25.   
  26. </manifest>   

 

activity程序:

[java] view plaincopy
  1. package sms.multithreaddownload;  
  2.   
  3. import java.io.File;  
  4.   
  5. import sms.multithreaddownload.bean.DownloadListener;  
  6. import sms.multithreaddownload.service.DownloadService;  
  7. import android.app.Activity;  
  8. import android.os.Bundle;  
  9. import android.os.Environment;  
  10. import android.os.Handler;  
  11. import android.os.Message;  
  12. import android.view.View;  
  13. import android.view.View.OnClickListener;  
  14. import android.widget.Button;  
  15. import android.widget.EditText;  
  16. import android.widget.ProgressBar;  
  17. import android.widget.TextView;  
  18. import android.widget.Toast;  
  19.   
  20. public class Main extends Activity {  
  21.     private EditText path;  
  22.     private TextView progress;  
  23.     private ProgressBar progressBar;  
  24.     private Handler handler = new UIHandler();  
  25.     private DownloadService servcie;  
  26.     private Button downButton;  
  27.     private Button pauseButton;  
  28.   
  29.     private final class UIHandler extends Handler {  
  30.         @Override  
  31.         public void handleMessage(Message msg) {  
  32.             switch (msg.what) {  
  33.                 case 1:  
  34.                     int downloaded_size = msg.getData().getInt("size");  
  35.                     progressBar.setProgress(downloaded_size);  
  36.                     int result = (int) ((float) downloaded_size / progressBar.getMax() * 100);  
  37.                     progress.setText(result + "%");  
  38.                     if (progressBar.getMax() == progressBar.getProgress()) {  
  39.                         Toast.makeText(getApplicationContext(), "下载完成", Toast.LENGTH_LONG).show();  
  40.                     }  
  41.             }  
  42.         }  
  43.     }  
  44.   
  45.     @Override  
  46.     public void onCreate(Bundle savedInstanceState) {  
  47.         super.onCreate(savedInstanceState);  
  48.         setContentView(R.layout.main);  
  49.         path = (EditText) this.findViewById(R.id.editText);  
  50.         progress = (TextView) this.findViewById(R.id.textView);  
  51.         progressBar = (ProgressBar) this.findViewById(R.id.progressBar);  
  52.         downButton = (Button) this.findViewById(R.id.downButton);  
  53.         pauseButton = (Button) this.findViewById(R.id.pauseButton);  
  54.         downButton.setOnClickListener(new DownloadButton());  
  55.         pauseButton.setOnClickListener(new PauseButton());  
  56.     }  
  57.   
  58.     private final class DownloadButton implements View.OnClickListener {  
  59.         @Override  
  60.         public void onClick(View v) {  
  61.             DownloadTask task;  
  62.             try {  
  63.                 task = new DownloadTask(path.getText().toString());  
  64.                 servcie.isPause = false;  
  65.                 v.setEnabled(false);  
  66.                 pauseButton.setEnabled(true);  
  67.                 new Thread(task).start();  
  68.             } catch (Exception e) {  
  69.                 e.printStackTrace();  
  70.             }  
  71.         }  
  72.     }  
  73.   
  74.     public class PauseButton implements OnClickListener {  
  75.         @Override  
  76.         public void onClick(View v) {  
  77.             servcie.isPause = true;  
  78.             v.setEnabled(false);  
  79.             downButton.setEnabled(true);  
  80.         }  
  81.     }  
  82.   
  83.     public void pause(View v) {  
  84.     }  
  85.   
  86.     private final class DownloadTask implements Runnable {  
  87.   
  88.         public DownloadTask(String target) throws Exception {  
  89.             if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {  
  90.                 File destination = Environment.getExternalStorageDirectory();  
  91.                 servcie = new DownloadService(target, destination, 3, getApplicationContext());  
  92.                 progressBar.setMax(servcie.fileSize);  
  93.             } else {  
  94.                 Toast.makeText(getApplicationContext(), "SD卡不存在或写保护!", Toast.LENGTH_LONG).show();  
  95.             }  
  96.         }  
  97.   
  98.         @Override  
  99.         public void run() {  
  100.             try {  
  101.                 servcie.download(new DownloadListener() {  
  102.   
  103.                     @Override  
  104.                     public void onDownload(int downloaded_size) {  
  105.                         Message message = new Message();  
  106.                         message.what = 1;  
  107.                         message.getData().putInt("size", downloaded_size);  
  108.                         handler.sendMessage(message);  
  109.                     }  
  110.   
  111.                 });  
  112.             } catch (Exception e) {  
  113.                 e.printStackTrace();  
  114.             }  
  115.   
  116.         }  
  117.     }  
  118. }  


工具类:

[java] view plaincopy
  1. package sms.multithreaddownload.bean;  
  2.   
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteOpenHelper;  
  6.   
  7. public class DBHelper extends SQLiteOpenHelper {  
  8.   
  9.     public DBHelper(Context context) {  
  10.         super(context, "MultiDownLoad.db"null1);  
  11.     }  
  12.   
  13.     @Override  
  14.     public void onCreate(SQLiteDatabase db) {  
  15.         db.execSQL("CREATE TABLE fileDownloading(_id integer primary key autoincrement,downPath varchar(100),threadId INTEGER,downLength INTEGER)");  
  16.     }  
  17.   
  18.     @Override  
  19.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  20.         // TODO Auto-generated method stub  
  21.   
  22.     }  
  23.   
  24. }  


 

[java] view plaincopy
  1. package sms.multithreaddownload.bean;  
  2.   
  3. public interface DownloadListener {  
  4.     public void onDownload(int downloaded_size);  
  5. }  


 

[java] view plaincopy
  1. package sms.multithreaddownload.bean;  
  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.   
  9. import sms.multithreaddownload.service.DownloadService;  
  10.   
  11. import android.util.Log;  
  12.   
  13. public final class MultiThreadDownload implements Runnable {  
  14.     public int id;  
  15.     private RandomAccessFile savedFile;  
  16.     private String path;  
  17.     /* 当前已下载量 */  
  18.     public int currentDownloadSize = 0;  
  19.     /* 下载状态 */  
  20.     public boolean finished;  
  21.     /* 用于监视下载状态 */  
  22.     private final DownloadService downloadService;  
  23.     /* 线程下载任务的起始点 */  
  24.     public int start;  
  25.     /* 线程下载任务的结束点 */  
  26.     private int end;  
  27.   
  28.     public MultiThreadDownload(int id, File savedFile, int block, String path, Integer downlength, DownloadService downloadService) throws Exception {  
  29.         this.id = id;  
  30.         this.path = path;  
  31.         if (downlength != nullthis.currentDownloadSize = downlength;  
  32.         this.savedFile = new RandomAccessFile(savedFile, "rwd");  
  33.         this.downloadService = downloadService;  
  34.         start = id * block + currentDownloadSize;  
  35.         end = (id + 1) * block;  
  36.     }  
  37.   
  38.     @Override  
  39.     public void run() {  
  40.         try {  
  41.             HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();  
  42.             conn.setConnectTimeout(5000);  
  43.             conn.setRequestMethod("GET");  
  44.             conn.setRequestProperty("Range""bytes=" + start + "-" + end); // 设置获取数据的范围  
  45.   
  46.             InputStream in = conn.getInputStream();  
  47.             byte[] buffer = new byte[1024];  
  48.             int len = 0;  
  49.             savedFile.seek(start);  
  50.             while (!downloadService.isPause && (len = in.read(buffer)) != -1) {  
  51.                 savedFile.write(buffer, 0, len);  
  52.                 currentDownloadSize += len;  
  53.             }  
  54.             savedFile.close();  
  55.             in.close();  
  56.             conn.disconnect();  
  57.             if (!downloadService.isPause) Log.i(DownloadService.TAG, "Thread " + (this.id + 1) + "finished");  
  58.             finished = true;  
  59.         } catch (Exception e) {  
  60.             e.printStackTrace();  
  61.             throw new RuntimeException("File downloading error!");  
  62.         }  
  63.     }  
  64. }  


service类:

[java] view plaincopy
  1. package sms.multithreaddownload.service;  
  2.   
  3. import java.io.File;  
  4. import java.io.RandomAccessFile;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7. import java.util.HashMap;  
  8. import java.util.List;  
  9. import java.util.Map;  
  10. import java.util.Map.Entry;  
  11. import java.util.UUID;  
  12. import java.util.concurrent.ConcurrentHashMap;  
  13. import java.util.regex.Matcher;  
  14. import java.util.regex.Pattern;  
  15.   
  16. import sms.multithreaddownload.bean.DBHelper;  
  17. import sms.multithreaddownload.bean.DownloadListener;  
  18. import sms.multithreaddownload.bean.MultiThreadDownload;  
  19.   
  20. import android.content.Context;  
  21. import android.database.Cursor;  
  22. import android.database.sqlite.SQLiteDatabase;  
  23.   
  24.   
  25. public class DownloadService {  
  26.     public static final String TAG = "tag";  
  27.     /* 用于查询数据库 */  
  28.     private DBHelper dbHelper;  
  29.     /* 要下载的文件大小 */  
  30.     public int fileSize;  
  31.     /* 每条线程需要下载的数据量 */  
  32.     private int block;  
  33.     /* 保存文件地目录 */  
  34.     private File savedFile;  
  35.     /* 下载地址 */  
  36.     private String path;  
  37.     /* 是否停止下载 */  
  38.     public boolean isPause;  
  39.     /* 线程数 */  
  40.     private MultiThreadDownload[] threads;  
  41.     /* 各线程已经下载的数据量 */  
  42.     private Map<Integer, Integer> downloadedLength = new ConcurrentHashMap<Integer, Integer>();  
  43.   
  44.     public DownloadService(String target, File destination, int thread_size, Context context) throws Exception {  
  45.         dbHelper = new DBHelper(context);  
  46.         this.threads = new MultiThreadDownload[thread_size];  
  47.         this.path = target;  
  48.         URL url = new URL(target);  
  49.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  50.         conn.setConnectTimeout(5000);  
  51.         conn.setRequestMethod("GET");  
  52.   
  53.         if (conn.getResponseCode() != 200) {  
  54.             throw new RuntimeException("server no response!");  
  55.         }  
  56.   
  57.         fileSize = conn.getContentLength();  
  58.         if (fileSize <= 0) {  
  59.             throw new RuntimeException("file is incorrect!");  
  60.         }  
  61.         String fileName = getFileName(conn);  
  62.         if (!destination.exists()) destination.mkdirs();  
  63.         // 构建一个同样大小的文件  
  64.         this.savedFile = new File(destination, fileName);  
  65.         RandomAccessFile doOut = new RandomAccessFile(savedFile, "rwd");  
  66.         doOut.setLength(fileSize);  
  67.         doOut.close();  
  68.         conn.disconnect();  
  69.   
  70.         // 计算每条线程需要下载的数据长度  
  71.         this.block = fileSize % thread_size == 0 ? fileSize / thread_size : fileSize / thread_size + 1;  
  72.         // 查询已经下载的记录  
  73.         downloadedLength = this.getDownloadedLength(path);  
  74.     }  
  75.   
  76.     private Map<Integer, Integer> getDownloadedLength(String path) {  
  77.         SQLiteDatabase db = dbHelper.getReadableDatabase();  
  78.         String sql = "SELECT threadId,downLength FROM fileDownloading WHERE downPath=?";  
  79.         Cursor cursor = db.rawQuery(sql, new String[] { path });  
  80.         Map<Integer, Integer> data = new HashMap<Integer, Integer>();  
  81.         while (cursor.moveToNext()) {  
  82.             data.put(cursor.getInt(0), cursor.getInt(1));  
  83.         }  
  84.         db.close();  
  85.         return data;  
  86.     }  
  87.   
  88.     private String getFileName(HttpURLConnection conn) {  
  89.         String fileName = path.substring(path.lastIndexOf("/") + 1, path.length());  
  90.         if (fileName == null || "".equals(fileName.trim())) {  
  91.             String content_disposition = null;  
  92.             for (Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) {  
  93.                 if ("content-disposition".equalsIgnoreCase(entry.getKey())) {  
  94.                     content_disposition = entry.getValue().toString();  
  95.                 }  
  96.             }  
  97.             try {  
  98.                 Matcher matcher = Pattern.compile(".*filename=(.*)").matcher(content_disposition);  
  99.                 if (matcher.find()) fileName = matcher.group(1);  
  100.             } catch (Exception e) {  
  101.                 fileName = UUID.randomUUID().toString() + ".tmp"// 默认名  
  102.             }  
  103.         }  
  104.         return fileName;  
  105.     }  
  106.   
  107.     public void download(DownloadListener listener) throws Exception {  
  108.         this.deleteDownloading(); // 先删除上次的记录,再重新添加  
  109.         for (int i = 0; i < threads.length; i++) {  
  110.             threads[i] = new MultiThreadDownload(i, savedFile, block, path, downloadedLength.get(i), this);  
  111.             new Thread(threads[i]).start();  
  112.         }  
  113.         this.saveDownloading(threads);  
  114.   
  115.         while (!isFinish(threads)) {  
  116.             Thread.sleep(900);  
  117.             if (listener != null) listener.onDownload(getDownloadedSize(threads));  
  118.             this.updateDownloading(threads);  
  119.         }  
  120.         if (!this.isPause) this.deleteDownloading();// 完成下载之后删除本次下载记录  
  121.     }  
  122.   
  123.     private void saveDownloading(MultiThreadDownload[] threads) {  
  124.         SQLiteDatabase db = dbHelper.getWritableDatabase();  
  125.         try {  
  126.             db.beginTransaction();  
  127.             for (MultiThreadDownload thread : threads) {  
  128.                 String sql = "INSERT INTO fileDownloading(downPath,threadId,downLength) values(?,?,?)";  
  129.                 db.execSQL(sql, new Object[] { path, thread.id, 0 });  
  130.             }  
  131.             db.setTransactionSuccessful();  
  132.         } finally {  
  133.             db.endTransaction();  
  134.             db.close();  
  135.         }  
  136.     }  
  137.   
  138.     private void deleteDownloading() {  
  139.         SQLiteDatabase db = dbHelper.getWritableDatabase();  
  140.         String sql = "DELETE FROM fileDownloading WHERE downPath=?";  
  141.         db.execSQL(sql, new Object[] { path });  
  142.         db.close();  
  143.     }  
  144.   
  145.     private void updateDownloading(MultiThreadDownload[] threads) {  
  146.         SQLiteDatabase db = dbHelper.getWritableDatabase();  
  147.         try {  
  148.             db.beginTransaction();  
  149.             for (MultiThreadDownload thread : threads) {  
  150.                 String sql = "UPDATE fileDownloading SET downLength=? WHERE threadId=? AND downPath=?";  
  151.                 db.execSQL(sql, new String[] { thread.currentDownloadSize + "", thread.id + "", path });  
  152.             }  
  153.             db.setTransactionSuccessful();  
  154.         } finally {  
  155.             db.endTransaction();  
  156.             db.close();  
  157.         }  
  158.     }  
  159.   
  160.     private int getDownloadedSize(MultiThreadDownload[] threads) {  
  161.         int sum = 0;  
  162.         for (int len = threads.length, i = 0; i < len; i++) {  
  163.             sum += threads[i].currentDownloadSize;  
  164.         }  
  165.         return sum;  
  166.     }  
  167.   
  168.     private boolean isFinish(MultiThreadDownload[] threads) {  
  169.         try {  
  170.             for (int len = threads.length, i = 0; i < len; i++) {  
  171.                 if (!threads[i].finished) {  
  172.                     return false;  
  173.                 }  
  174.             }  
  175.             return true;  
  176.         } catch (Exception e) {  
  177.             return false;  
  178.         }  
  179.     }  
  180. }  


运行效果:

 


源码下载地址

 

http://blog.csdn.net/shimiso/article/details/8448544  android 多线程断点续传下载 三

原文地址:点击打开链接

原创粉丝点击