android 多线程断点续传下载 二

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

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<EditText
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:id="@+id/editText"
		android:text="http://gongxue.cn/yingyinkuaiche/UploadFiles_9323/201008/2010082909434077.mp3"
	/>
	<LinearLayout
		android:orientation="horizontal"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
	>
		<Button
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:id="@+id/downButton"
			android:text="Download"
		/>
		<Button
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:id="@+id/pauseButton"
			android:enabled="false"
			android:text="Pause"
		/>
	</LinearLayout>
	
	<ProgressBar
		android:layout_width="match_parent"
		android:layout_height="18dp"
		style="?android:attr/progressBarStyleHorizontal"
		android:id="@+id/progressBar"
	/>
	<TextView
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:id="@+id/textView"
		android:gravity="center"
	/>
</LinearLayout>

 

String.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Main!</string>
    <string name="app_name">多线程断点续传下载</string>
</resources>


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

</manifest> 

 

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<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://blog.csdn.net/shimiso/article/details/8448544  android 多线程断点续传下载 三

  转载请标明出处 http://blog.csdn.net/shimiso 

技术交流群:66756039

  • 7
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 18
    评论
实现Android多线程断点续传下载涉及以下几点: 1. 创建多个线程进行下载,每个线程负责下载一部分文件,并在下载过程中进行异常处理; 2. 确定每个线程下载的起始位置和结束位置; 3. 使用RandomAccessFile类进行文件的读写操作,以便能够随机访问文件,实现断点续传。 下面给出详细解决方案: 1. 创建多个线程进行下载Android中可以使用AsyncTask或者Thread来创建多个线程进行下载。使用AsyncTask比较方便,可以在doInBackground()方法中进行下载操作,而Thread需要手动创建和管理线程。不管使用哪种方式,都需要在下载过程中进行异常处理,防止下载过程中出现异常导致程序崩溃。 2. 确定每个线程下载的起始位置和结束位置 为了防止多个线程同时下载同一部分文件,需要确定每个线程下载的起始位置和结束位置。可以通过计算文件的总长度和线程数来确定每个线程下载的区间。例如,文件长度为1000,线程数为4,那么每个线程下载的区间为0-249、250-499、500-749、750-999。 3. 使用RandomAccessFile类进行文件的读写操作,实现断点续传 为了实现断点续传,需要能够随机访问文件。可以使用Java中的RandomAccessFile类来实现。在下载过程中,每个线程需要记录自己下载的进度,并在下载完成后将进度保存到本地。当用户暂停下载后,可以通过读取保存的进度信息来恢复下载。 下面是一个简单的实现代码,供参考: ```java public class DownloadTask extends AsyncTask<String, Integer, Integer> { private int threadCount = 3; // 线程数 private int progress; // 下载进度 private String url; // 下载链接 private String fileName; // 保存的文件名 private Context context; private boolean isPause = false; // 是否暂停下载 private boolean isCancel = false; // 是否取消下载 public DownloadTask(Context context, String url, String fileName) { this.context = context; this.url = url; this.fileName = fileName; } @Override protected Integer doInBackground(String... params) { HttpURLConnection conn = null; RandomAccessFile raf = null; InputStream is = null; try { URL url = new URL(this.url); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); int code = conn.getResponseCode(); if (code == 200) { int length = conn.getContentLength(); File file = new File(context.getFilesDir(), fileName); raf = new RandomAccessFile(file, "rwd"); raf.setLength(length); int blockSize = length / threadCount; for (int i = 0; i < threadCount; i++) { int start = i * blockSize; int end = (i + 1) * blockSize - 1; if (i == threadCount - 1) { end = length; } new DownloadThread(i, start, end).start(); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } if (raf != null) { raf.close(); } if (conn != null) { conn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } return progress; } @Override protected void onPostExecute(Integer integer) { super.onPostExecute(integer); if (integer == 100) { Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show(); } else if (isCancel) { Toast.makeText(context, "下载已取消", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show(); } } public void pause() { isPause = true; } public void cancel() { isCancel = true; isPause = false; } private class DownloadThread extends Thread { private int threadId; private int start; private int end; private int progress; public DownloadThread(int threadId, int start, int end) { this.threadId = threadId; this.start = start; this.end = end; } @Override public void run() { HttpURLConnection conn = null; RandomAccessFile raf = null; InputStream is = null; try { File file = new File(context.getFilesDir(), fileName); raf = new RandomAccessFile(file, "rwd"); raf.seek(start); URL url = new URL(DownloadTask.this.url); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); conn.setRequestProperty("Range", "bytes=" + start + "-" + end); if (conn.getResponseCode() == 206) { is = conn.getInputStream(); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) != -1) { if (isPause || isCancel) { return; } raf.write(buffer, 0, len); progress += len; publishProgress(progress * 100 / (end - start + 1)); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } if (raf != null) { raf.close(); } if (conn != null) { conn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } } } } ``` 在这个实现中,DownloadTask类继承自AsyncTask类,用于启动多个下载线程。在doInBackground()方法中,通过计算文件的总长度和线程数来确定每个线程下载的区间,并创建DownloadThread类的实例来启动下载线程。 DownloadThread类继承自Thread类,用于执行具体的下载操作。在run()方法中,设置请求头Range字段,以便服务器能够返回指定区间的数据。在下载过程中,每个线程需要记录自己下载的进度,并通过publishProgress()方法将进度信息传递给DownloadTask类,以便更新UI。在下载完成后,将进度信息保存到本地文件中。 在DownloadTask类中,还提供了pause()和cancel()方法,用于暂停和取消下载。在DownloadThread类的run()方法中,判断是否需要暂停或取消下载,并在需要时直接返回,以便退出线程。在onPostExecute()方法中,根据下载进度来显示下载结果。 总的来说,实现Android多线程断点续传下载需要考虑很多细节问题,需要进行仔细的设计和实现。上面的示例代码只是一个简单的实现,并不能满足所有的需求,需要根据具体的需求进行修改和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值