android 之断点续传详解三部曲之[二] → 断点续传下载

简介: <p><span style="color:rgb(54,46,43); line-height:26px"><span style="font-family:Microsoft YaHei; font-size:18px"><span style="white-space:pre"></span>在<span style="color:rgb(54,46,43); font-family

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

和上一篇中一样,先来布局文件:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="http://gongxue.cn/yingyinkuaiche/UploadFiles_9323/201008/2010082909434077.mp3" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/downButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Download" />

        <Button
            android:id="@+id/pauseButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:enabled="false"
            android:text="Pause" />
    </LinearLayout>

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="18dp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="#fff"
        android:textSize="20.0sp" />

</LinearLayout>

配置文件:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="sms.multithreaddownload"
    android:versionCode="1"
    android:versionName="1.0" >

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".Main"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <uses-library android:name="android.test.runner" />
    </application>

    <uses-sdk android:minSdkVersion="8" />

    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="sms.multithreaddownload" />
    <!-- 访问网络的权限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- SDCard写数据的权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

</manifest>

接下来是activity:

Main.java

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 final Handler handler = new UIHandler();
	private DownloadService servcie;
	private Button downButton;
	private Button pauseButton;

	private final class UIHandler extends Handler {

		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();
				}
			}
		}
	}

	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 {

		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 {

		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();
			}
		}

		public void run() {
			try {
				servcie.download(new DownloadListener() {

					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();
			}

		}
	}
}

工具类:

DBHelper.java

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

	}

}

DownloadListener.java

package sms.multithreaddownload.bean;

public interface DownloadListener {
	public void onDownload(int downloaded_size);
}

MultiThreadDownload.java

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;
	}

	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类:

DownloadService.java

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<Integer, Integer> downloadedLength = new ConcurrentHashMap<Integer, Integer>();

	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 <= 0) {
			throw new RuntimeException("file is incorrect!");
		}
		String fileName = getFileName(conn);
		if (!destination.exists())
			destination.mkdirs();
		// 构建一个同样大小的文件
		this.savedFile = new File(destination, fileName);
		RandomAccessFile doOut = new RandomAccessFile(savedFile, "rwd");
		doOut.setLength(fileSize);
		doOut.close();
		conn.disconnect();

		// 计算每条线程需要下载的数据长度
		this.block = fileSize % thread_size == 0 ? fileSize / thread_size : fileSize / thread_size + 1;
		// 查询已经下载的记录
		downloadedLength = this.getDownloadedLength(path);
	}

	private Map<Integer, Integer> getDownloadedLength(String path) {
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		String sql = "SELECT threadId,downLength FROM fileDownloading WHERE downPath=?";
		Cursor cursor = db.rawQuery(sql, new String[] { path });
		Map<Integer, Integer> data = new HashMap<Integer, Integer>();
		while (cursor.moveToNext()) {
			data.put(cursor.getInt(0), cursor.getInt(1));
		}
		db.close();
		return data;
	}

	private String getFileName(HttpURLConnection conn) {
		String fileName = path.substring(path.lastIndexOf("/") + 1, path.length());
		if (fileName == null || "".equals(fileName.trim())) {
			String content_disposition = null;
			for (Entry<String, List<String>> entry : conn.getHeaderFields().entrySet()) {
				if ("content-disposition".equalsIgnoreCase(entry.getKey())) {
					content_disposition = entry.getValue().toString();
				}
			}
			try {
				Matcher matcher = Pattern.compile(".*filename=(.*)").matcher(content_disposition);
				if (matcher.find())
					fileName = matcher.group(1);
			} catch (Exception e) {
				fileName = UUID.randomUUID().toString() + ".tmp"; // 默认名
			}
		}
		return fileName;
	}

	public void download(DownloadListener listener) throws Exception {
		this.deleteDownloading(); // 先删除上次的记录,再重新添加
		for (int i = 0; i < threads.length; i++) {
			threads[i] = new MultiThreadDownload(i, savedFile, block, path, downloadedLength.get(i), this);
			new Thread(threads[i]).start();
		}
		this.saveDownloading(threads);

		while (!isFinish(threads)) {
			Thread.sleep(900);
			if (listener != null)
				listener.onDownload(getDownloadedSize(threads));
			this.updateDownloading(threads);
		}
		if (!this.isPause)
			this.deleteDownloading();// 完成下载之后删除本次下载记录
	}

	private void saveDownloading(MultiThreadDownload[] threads) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		try {
			db.beginTransaction();
			for (MultiThreadDownload thread : threads) {
				String sql = "INSERT INTO fileDownloading(downPath,threadId,downLength) values(?,?,?)";
				db.execSQL(sql, new Object[] { path, thread.id, 0 });
			}
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
			db.close();
		}
	}

	private void deleteDownloading() {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		String sql = "DELETE FROM fileDownloading WHERE downPath=?";
		db.execSQL(sql, new Object[] { path });
		db.close();
	}

	private void updateDownloading(MultiThreadDownload[] threads) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		try {
			db.beginTransaction();
			for (MultiThreadDownload thread : threads) {
				String sql = "UPDATE fileDownloading SET downLength=? WHERE threadId=? AND downPath=?";
				db.execSQL(sql, new String[] { thread.currentDownloadSize + "", thread.id + "", path });
			}
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
			db.close();
		}
	}

	private int getDownloadedSize(MultiThreadDownload[] threads) {
		int sum = 0;
		for (int len = threads.length, i = 0; i < len; i++) {
			sum += threads[i].currentDownloadSize;
		}
		return sum;
	}

	private boolean isFinish(MultiThreadDownload[] threads) {
		try {
			for (int len = threads.length, i = 0; i < len; i++) {
				if (!threads[i].finished) {
					return false;
				}
			}
			return true;
		} catch (Exception e) {
			return false;
		}
	}
}

下面给上效果图:




源码下载地址:http://download.csdn.net/detail/gulaer/5004954  源码中包含"android 之断点续传详解三部曲之[二] → 断点续传下载"和"android 之断点续传详解三部曲之[三] → 多任务同时下载"代码.

原文地址:http://blog.csdn.net/shimiso/article/details/6763986 非常感谢原作者.


相关文章
|
3月前
|
Ubuntu 开发工具 Android开发
Repo下载AOSP源码:基于ubuntu22.04 环境配置,android-12.0.0_r32
本文介绍了在基于Ubuntu 22.04的环境下配置Python 3.9、安装repo工具、下载和同步AOSP源码包以及处理repo同步错误的详细步骤。
202 0
Repo下载AOSP源码:基于ubuntu22.04 环境配置,android-12.0.0_r32
|
10天前
|
Java 程序员 开发工具
Android|修复阿里云播放器下载不回调的问题
虽然 GC 带来了很多便利,但在实际编码时,我们也需要注意对象的生命周期管理,该存活的存活,该释放的释放,避免因为 GC 导致的问题。
20 2
|
3月前
|
监控 Java API
Android经典实战之OkDownload:一个经典强大的文件下载开源库,支持断点续传
本文介绍的 OkDownload 是一个专为 Android 设计的开源下载框架,支持多线程下载、断点续传和任务队列管理等功能,具备可靠性、灵活性和高性能特点。它提供了多种配置选项和监听器,便于开发者集成和扩展。尽管已多年未更新,但依然适用于大多数文件下载需求。
308 1
|
3月前
|
开发工具 uml git
AOSP源码下载方法,解决repo sync错误:android-13.0.0_r82
本文分享了下载AOSP源码的方法,包括如何使用repo工具和处理常见的repo sync错误,以及配置Python环境以确保顺利同步特定版本的AOSP代码。
358 0
AOSP源码下载方法,解决repo sync错误:android-13.0.0_r82
|
3月前
|
API 开发工具 Android开发
Android源码下载
Android源码下载
414 0
|
3月前
|
存储 监控 数据库
Android经典实战之OkDownload的文件分段下载及合成原理
本文介绍了 OkDownload,一个高效的 Android 下载引擎,支持多线程下载、断点续传等功能。文章详细描述了文件分段下载及合成原理,包括任务创建、断点续传、并行下载等步骤,并展示了如何通过多种机制保证下载的稳定性和完整性。
85 0
|
3月前
|
Ubuntu 开发工具 Android开发
Repo下载、编译AOSP源码:基于Ubuntu 21.04,android-12.1.0_r27
文章记录了作者在Ubuntu 21.04服务器上配置环境、下载并编译基于Android 12.1.0_r27版本的AOSP源码的过程,包括解决编译过程中遇到的问题和错误处理方法。
146 0
|
5月前
|
Android开发 Windows
如何离线下载 Microsoft Corporation II Windows Subsystem for Android
如何离线下载 Microsoft Corporation II Windows Subsystem for Android
114 1
|
5月前
|
开发工具 Android开发
Android studio历史版本下载
Android studio历史版本下载
595 0