android下多线程下载,断点续传,及暂停按钮

package cn.itcast.mutiledownload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
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 DemoActivity extends Activity implements OnClickListener {

	private ProgressBar pb;
	private Button bt;
	private TextView tv;
	private EditText et;
	boolean flag = true;
	boolean stopflag = false;
	private Handler handler = new Handler() {

	@Override
	public void handleMessage(Message msg) {
	//初始值为0; pb.setMax(len);
	//里面的进度条的变化
pb.setProgress(total);
//文件的总长度.
int max = pb.getMax();
	//变化的total大于=max.为保险起见.
if (total >= (max - 1)) {
	total = max;
	flag = false;
	}
	//total是变化的.
int result = total * 100 / max;
	//
	tv.setText("当前进度 :" + result + "%");

	super.handleMessage(msg);
	}
	};
//定义全局变量total.
	int total = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);
	pb = (ProgressBar) this.findViewById(R.id.pb);
	bt = (Button) this.findViewById(R.id.bt);
	tv = (TextView) this.findViewById(R.id.tv_process);
	et = (EditText) this.findViewById(R.id.et);
	bt.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
	switch (v.getId()) {
	case R.id.bt:
	// 创建一个子线程 定期的更新ui

//初始状态,里面的按钮的内容是开始下载,当点击按钮的时候,文本设
//开始下载.就不执行return方法.
if("开始下载".equals(bt.getText().toString())){
	bt.setText("暂停");
stopflag = false; 
	}
	else {
	//就return暂停了.若果stopflag为真的话,就执行return方法. 
bt.setText("开始下载");
stopflag = true;
	}
	//在onclick按钮点击的时候开始的第一件事,子线程更新ui.
	new Thread() {
	@Override
	public void run() {
	super.run();
	//flag初始值为true.
	while (flag) {
	try {
	sleep(1000);
	// 如果total > = 文件长度
//每隔一秒发送消息.
Message msg = new Message();
	//msg不带东西.
handler.sendMessage(msg);
	} catch (InterruptedException e) {
	e.printStackTrace();
	}

	}
	}
	}.start();

	// 开始执行下载的操作
String path = et.getText().toString().trim();
	if ("".equals(path)) {
	Toast.makeText(this, "路径不能为空", 1).show();
	return;
	}
	// 在onclick按钮点击的时候开始的第二件事,开启另外3个子线程.下载.
try {
	//在线程里面穿件连接
URL url = new URL(path);
	HttpURLConnection conn = (HttpURLConnection) url
	.openConnection();
	conn.setRequestMethod("GET");
	conn.setConnectTimeout(5000);
	conn.setRequestProperty("User-Agent",
	"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
	int code = conn.getResponseCode();
	if (code == 200) {
	int len = conn.getContentLength();
	RandomAccessFile file = new RandomAccessFile(
	"/mnt/sdcard/" + getFilenName(path), "rwd");
	// 1.设置本地文件大小跟服务器的文件大小一致
file.setLength(len);
	// 主线程中,设置进度条的最大值
pb.setMax(len);

	// 2 .假设开启3 个线程
int threadnumber = 3;
	int blocksize = len / threadnumber;
	/**
	* 线程1 0~ blocksize 线程2 1*bolocksize ~ 2*blocksize 线程3
	* 2*blocksize ~ 文件末尾
*/
for (int i = 0; i < threadnumber; i++) {
	int startposition = i * blocksize;
	int endpositon = (i + 1) * blocksize;
	if (i == (threadnumber - 1)) {
	// 最后一个线程
endpositon = len;
	}
//开启3个线程.
DownLoadTask task = new DownLoadTask(i, path,
	startposition, endpositon);
	task.start();
	}

	}
	} catch (Exception e) {
	Toast.makeText(this, "下载出现异常", 0).show();
	e.printStackTrace();
	}

	break;
	}

	}

	class DownLoadTask extends Thread {

	int threadid;
	String filepath;
	int startposition;
	int endpositon;

	public DownLoadTask(int threadid, String filepath, int startposition,
	int endpositon) {
	this.threadid = threadid;
	this.filepath = filepath;
	this.startposition = startposition;
	this.endpositon = endpositon;

	}

	@Override
	public void run() {
	try {
	// 创建一个文件对象 ,记录当前某个文件的下载位置
File postionfile = new File("/mnt/sdcard/" + threadid + ".txt");
	URL url = new URL(filepath);
	HttpURLConnection conn = (HttpURLConnection) url
	.openConnection();
	System.out.println("线程" + threadid + "正在下载 " + "开始位置 : "
	+ startposition + "结束位置 " + endpositon);
//如果postionfile存在的话,就证明以前有下载的一部分文件.
if (postionfile.exists()) {
	//从文件中读取下载的地址.
FileInputStream fis = new FileInputStream(postionfile);
	//流转化为byte.
	byte[] result = StreamTool.getBytes(fis);
	//转化为str.
	String str = new String(result);
	if (!"".equals(str)) {
	//转化为int.
	int newstartposition = Integer.parseInt(str);
	//为了保险起见.
if (newstartposition > startposition) {
	//从以前的地址开始下载.
startposition = newstartposition;
	}
	}
	}

	// "Range", "bytes=2097152-4194303")
	//
	conn.setRequestProperty("Range", "bytes=" + startposition + "-"
	+ endpositon);
	conn.setRequestMethod("GET");
	conn.setConnectTimeout(5000);
	//下载文件最好设置user-Agent.
	conn.setRequestProperty("User-Agent",
	"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
	InputStream is = conn.getInputStream();
	RandomAccessFile file = new RandomAccessFile("/mnt/sdcard/"
	+ getFilenName(filepath), "rwd");
	// 设置 数据从文件哪个位置开始写
file.seek(startposition);
	byte[] buffer = new byte[1024];
	int len = 0;
	// currentPostion代表当前读到的服务器数据的位置 ,
// 同时这个值写出去的,也就是已经存储的文件的位置
//while循环就是表示下载.
int currentPostion = startposition;

//len=is.read(buffer).len是变化的,所以total += len;是连续的.
while ((len = is.read(buffer)) != -1) {
	//暂停 stopflag为false.
	if (stopflag) {
	return;
	}
	file.write(buffer, 0, len);

	synchronized (DemoActivity.this) {
	//total=total+len;
	//DemoActivity.this是锁.同步当前的activity.
	total += len;

	}
	//这里目的是做断点下载的.防止手机停电,电脑死机.下次没有保存数据.
//currentPostion =currentPostion+ len;
	//每一次写的时候,当前的位置就增减len.
	currentPostion += len;
	// 需要把currentPostion 信息给持久化到存储设备
String position = currentPostion + "";

	FileOutputStream fos = new FileOutputStream(postionfile);
	//将位置写到文件里面.
	//将文件的position写入postionfile.
	fos.write(position.getBytes());
	fos.flush();
	fos.close();
	}

	file.close();
	System.out.println("线程" + threadid + "下载完毕");
	// 当线程下载完毕后 把文件删除掉
if (postionfile.exists()) {
	postionfile.delete();
	}

	} catch (Exception e) {
	e.printStackTrace();
	}

	super.run();
	}

	}

	public String getFilenName(String path) {
	int start = path.lastIndexOf("/") + 1;
	return path.substring(start, path.length());
	}
}
<pre class="java" name="code">package cn.itcast.mutiledownload;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTool {
	/**
	 * 把一个inputstream里面的内容转化成一个byte[] 
	 */
	
	public static byte[] getBytes(InputStream is) throws Exception{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while((len = is.read(buffer))!=-1){
			bos.write(buffer, 0, len);
		}
		is.close();
		bos.flush();
		byte[] result = bos.toByteArray();
		System.out.println(new String(result));
		return  result;
	}
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值