您当前的位置: 首页 >  android

xiangzhihong8

暂无认证

  • 5浏览

    0关注

    1324博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

android多线程下载2

xiangzhihong8 发布时间:2013-12-03 09:11:51 ,浏览量:5

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

main.xml:

[html] view plain copy
  1.   
  2.   
  3.       
  4.       
  5.           
  6.           
  7.       
  8.       
  9.       
  10.       
  11.   

 

String.xml:

[html] view plain copy
  1.   
  2.   
  3.     Hello World, Main!  
  4.     多线程断点续传下载  
  5.   

AndroidManifest.xml:

[html] view plain copy
  1.   
  2.   
  3.       
  4.           
  5.               
  6.                   
  7.                   
  8.               
  9.           
  10.        
  11.       
  12.       
  13.       
  14.       
  15.       
  16.       
  17.       
  18.       
  19.   
  20.    

 

activity程序:

[java] view plain copy
  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 plain copy
  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", null, 1);  
  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 plain copy
  1. package sms.multithreaddownload.bean;  
  2.   
  3. public interface DownloadListener {  
  4.     public void onDownload(int downloaded_size);  
  5. }  

 

[java] view plain copy
  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 != null) this.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 plain copy
  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 downloadedLength = new ConcurrentHashMap();  
  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 
关注
打赏
1482932726
查看更多评论
立即登录/注册

微信扫码登录

0.0802s