在上一集中,我们简单介绍了如何创建多任务下载,但那种还不能拿来实用,这一集我们重点通过代码为大家展示如何创建多线程断点续传下载,这在实际项目中很常用.
main.xml:
String.xml:
- Hello World, Main!
- 多线程断点续传下载
AndroidManifest.xml:
activity程序:
- package sms.multithreaddownload;
- import java.io.File;
- import sms.multithreaddownload.bean.DownloadListener;
- import sms.multithreaddownload.service.DownloadService;
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Environment;
- import android.os.Handler;
- import android.os.Message;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.ProgressBar;
- import android.widget.TextView;
- import android.widget.Toast;
- public class Main extends Activity {
- private EditText path;
- private TextView progress;
- private ProgressBar progressBar;
- private Handler handler = new UIHandler();
- private DownloadService servcie;
- private Button downButton;
- private Button pauseButton;
- private final class UIHandler extends Handler {
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case 1:
- int downloaded_size = msg.getData().getInt("size");
- progressBar.setProgress(downloaded_size);
- int result = (int) ((float) downloaded_size / progressBar.getMax() * 100);
- progress.setText(result + "%");
- if (progressBar.getMax() == progressBar.getProgress()) {
- Toast.makeText(getApplicationContext(), "下载完成", Toast.LENGTH_LONG).show();
- }
- }
- }
- }
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- path = (EditText) this.findViewById(R.id.editText);
- progress = (TextView) this.findViewById(R.id.textView);
- progressBar = (ProgressBar) this.findViewById(R.id.progressBar);
- downButton = (Button) this.findViewById(R.id.downButton);
- pauseButton = (Button) this.findViewById(R.id.pauseButton);
- downButton.setOnClickListener(new DownloadButton());
- pauseButton.setOnClickListener(new PauseButton());
- }
- private final class DownloadButton implements View.OnClickListener {
- @Override
- public void onClick(View v) {
- DownloadTask task;
- try {
- task = new DownloadTask(path.getText().toString());
- servcie.isPause = false;
- v.setEnabled(false);
- pauseButton.setEnabled(true);
- new Thread(task).start();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public class PauseButton implements OnClickListener {
- @Override
- public void onClick(View v) {
- servcie.isPause = true;
- v.setEnabled(false);
- downButton.setEnabled(true);
- }
- }
- public void pause(View v) {
- }
- private final class DownloadTask implements Runnable {
- public DownloadTask(String target) throws Exception {
- if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
- File destination = Environment.getExternalStorageDirectory();
- servcie = new DownloadService(target, destination, 3, getApplicationContext());
- progressBar.setMax(servcie.fileSize);
- } else {
- Toast.makeText(getApplicationContext(), "SD卡不存在或写保护!", Toast.LENGTH_LONG).show();
- }
- }
- @Override
- public void run() {
- try {
- servcie.download(new DownloadListener() {
- @Override
- public void onDownload(int downloaded_size) {
- Message message = new Message();
- message.what = 1;
- message.getData().putInt("size", downloaded_size);
- handler.sendMessage(message);
- }
- });
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
工具类:
- package sms.multithreaddownload.bean;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- public class DBHelper extends SQLiteOpenHelper {
- public DBHelper(Context context) {
- super(context, "MultiDownLoad.db", null, 1);
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- db.execSQL("CREATE TABLE fileDownloading(_id integer primary key autoincrement,downPath varchar(100),threadId INTEGER,downLength INTEGER)");
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- // TODO Auto-generated method stub
- }
- }
- package sms.multithreaddownload.bean;
- public interface DownloadListener {
- public void onDownload(int downloaded_size);
- }
- package sms.multithreaddownload.bean;
- import java.io.File;
- import java.io.InputStream;
- import java.io.RandomAccessFile;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import sms.multithreaddownload.service.DownloadService;
- import android.util.Log;
- public final class MultiThreadDownload implements Runnable {
- public int id;
- private RandomAccessFile savedFile;
- private String path;
- /* 当前已下载量 */
- public int currentDownloadSize = 0;
- /* 下载状态 */
- public boolean finished;
- /* 用于监视下载状态 */
- private final DownloadService downloadService;
- /* 线程下载任务的起始点 */
- public int start;
- /* 线程下载任务的结束点 */
- private int end;
- public MultiThreadDownload(int id, File savedFile, int block, String path, Integer downlength, DownloadService downloadService) throws Exception {
- this.id = id;
- this.path = path;
- if (downlength != null) this.currentDownloadSize = downlength;
- this.savedFile = new RandomAccessFile(savedFile, "rwd");
- this.downloadService = downloadService;
- start = id * block + currentDownloadSize;
- end = (id + 1) * block;
- }
- @Override
- public void run() {
- try {
- HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
- conn.setConnectTimeout(5000);
- conn.setRequestMethod("GET");
- conn.setRequestProperty("Range", "bytes=" + start + "-" + end); // 设置获取数据的范围
- InputStream in = conn.getInputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- savedFile.seek(start);
- while (!downloadService.isPause && (len = in.read(buffer)) != -1) {
- savedFile.write(buffer, 0, len);
- currentDownloadSize += len;
- }
- savedFile.close();
- in.close();
- conn.disconnect();
- if (!downloadService.isPause) Log.i(DownloadService.TAG, "Thread " + (this.id + 1) + "finished");
- finished = true;
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException("File downloading error!");
- }
- }
- }
service类:
- package sms.multithreaddownload.service;
- import java.io.File;
- import java.io.RandomAccessFile;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
- import java.util.UUID;
- import java.util.concurrent.ConcurrentHashMap;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import sms.multithreaddownload.bean.DBHelper;
- import sms.multithreaddownload.bean.DownloadListener;
- import sms.multithreaddownload.bean.MultiThreadDownload;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- public class DownloadService {
- public static final String TAG = "tag";
- /* 用于查询数据库 */
- private DBHelper dbHelper;
- /* 要下载的文件大小 */
- public int fileSize;
- /* 每条线程需要下载的数据量 */
- private int block;
- /* 保存文件地目录 */
- private File savedFile;
- /* 下载地址 */
- private String path;
- /* 是否停止下载 */
- public boolean isPause;
- /* 线程数 */
- private MultiThreadDownload[] threads;
- /* 各线程已经下载的数据量 */
- private Map downloadedLength = new ConcurrentHashMap();
- public DownloadService(String target, File destination, int thread_size, Context context) throws Exception {
- dbHelper = new DBHelper(context);
- this.threads = new MultiThreadDownload[thread_size];
- this.path = target;
- URL url = new URL(target);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setConnectTimeout(5000);
- conn.setRequestMethod("GET");
- if (conn.getResponseCode() != 200) {
- throw new RuntimeException("server no response!");
- }
- fileSize = conn.getContentLength();
- if (fileSize
关注打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?
立即登录/注册


微信扫码登录