android 下载资源代码

package com.example.multilelinedownload2;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
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 MainActivity extends Activity implements OnClickListener {
public static int threadcount;
private EditText et;
private Button btn_download, btn_stop;
private TextView tv;
private ProgressBar pb;
private int pbtotal; // 定义进度条的总长度
public boolean flag = true;
public int totallen;
public static final int ERROR = 404;
public static final int DOWNLOAD_FINISH = 200;


private Handler handler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
int progress = pbtotal * 100 / totallen;
String progressstr = "当前进度:" + progress + "%";
tv.setText(progressstr);
if (msg.what == ERROR) { // anr
Toast.makeText(getApplicationContext(), "获取文件长度失败", 0).show();
btn_download.setClickable(true);
btn_download.setEnabled(true);
return;
}
if (msg.what == DOWNLOAD_FINISH) {
btn_download.setClickable(true);
btn_download.setEnabled(true);
btn_stop.setClickable(false);
btn_stop.setEnabled(false);
return;
}
}
};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et = (EditText) findViewById(R.id.path);
btn_download = (Button) findViewById(R.id.btn_download);
btn_stop = (Button) findViewById(R.id.btn_stop);
tv = (TextView) findViewById(R.id.tv);
pb = (ProgressBar) findViewById(R.id.pb);


btn_download.setOnClickListener(this);
btn_stop.setOnClickListener(this);


}


@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_stop:
flag = false;
btn_stop.setClickable(false);
btn_stop.setEnabled(false);
btn_download.setClickable(true);
btn_download.setEnabled(true);
break;
case R.id.btn_download:
final String path = et.getText().toString().trim();// 获取用户输入地址
if ("".equals(path)) {
Toast.makeText(this, "路径不能为空", 0).show();
return;
} else {
btn_download.setClickable(false);
btn_download.setEnabled(false);
btn_stop.setClickable(true);
btn_stop.setEnabled(true);
new Thread() {
public void run() {
try {
pbtotal = 0;
flag = true;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");// 设置请求方式
conn.setConnectTimeout(5000); // 设置获取响应码的时间
int len = conn.getContentLength(); // 获取相应数据的长度
totallen = len;
pb.setMax(len); // 设置进度条的最大值
System.out.println("下载的文件的长度是:" + len);
// 在客户端创建一个大小跟服务区端文件一样的资源
File file = new File(
Environment.getExternalStorageDirectory(),
getFileName(path));
RandomAccessFile randomfile = new RandomAccessFile(
file, "rwd");
randomfile.setLength(len);
// 假设开启5个子线程
int blocksize = len / 5;
threadcount = 0;
for (int i = 1; i <= 5; i++) {
int startsize = (i - 1) * blocksize;
int endsize = (i) * blocksize - 1;
if (i == 5) {
endsize = len;
}
new Thread(new DownLoadTask(i, startsize,
endsize, path)).start();
// 解决所有的子线程全部执行完毕后,在把所有的i.txt文件删除
}
} catch (Exception e) {
// Toast.makeText(getBaseContext(),
// "下载出错了",0).show();
Message msg = new Message();
msg.what = ERROR;
handler.sendMessage(msg);
e.printStackTrace();
}
}
}.start();
}
break;
}
}


public String getFileName(String path) {
int s = path.lastIndexOf("/") + 1;
return path.substring(s);
}


public synchronized void setProgressbarProgress(int len) {
pbtotal += len;
pb.setProgress(pbtotal);
}


class DownLoadTask implements Runnable {
private int id, startsize, endsize;
private String path;


public DownLoadTask(int id, int startsize, int endsize, String path) {
super();
this.id = id; // 线程的id
this.startsize = startsize;
this.endsize = endsize;
this.path = path;
}


@Override
public void run() {


try {
// 每一个线程创建执行时都创建一个id.txt的文件,这个文件用来记载当前线程的下载进度。
File idfile = new File("/mnt/sdcard/" + id + ".txt");
if (idfile.exists()) {
FileInputStream fis = new FileInputStream(idfile);
ByteArrayOutputStream boas = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) != -1) {
boas.write(buffer, 0, len);
}
fis.close();
boas.close();
byte[] result = boas.toByteArray();
String numberstr = new String(result);
if (numberstr != null && (!"".equals(numberstr))) {
int startposition = Integer.parseInt(numberstr);
if (startposition > startsize) {
int currentpostion = startposition - startsize;
setProgressbarProgress(currentpostion); // 更新进度条
handler.sendEmptyMessage(0); // 通知主线程更新文本
startsize = startposition; // 重新指定下载的开始位置
}
}
}


URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");// 设置请求方式
conn.setConnectTimeout(5000); // 设置获取响应码的时间
// 指定当前线程从服务器上的哪个位置下载
conn.setRequestProperty("Range", "bytes=" + startsize + "-"
+ endsize);
System.out.println("文件下载的开始位置:" + startsize + "     结束位置:"
+ endsize);
InputStream is = conn.getInputStream();


File file = new File(Environment.getExternalStorageDirectory(),
getFileName(path));
RandomAccessFile randomfile = new RandomAccessFile(file, "rwd");
randomfile.seek(startsize);
byte[] buffer = new byte[1024];
int len = 0;
int tatol = 0;
while ((len = is.read(buffer)) != -1) {
randomfile.write(buffer, 0, len);
tatol += len;
FileOutputStream idfos = new FileOutputStream(idfile);
idfos.write(("" + (startsize + tatol)).getBytes());
setProgressbarProgress(len); // 更新进度条
handler.sendEmptyMessage(0); // 通知主线程更新文本
idfos.flush();
idfos.close();
if (!flag) {
return;
}
}
randomfile.close();
is.close();
System.out.println("线程  " + id + "      下载完毕");


/*
* if(idfile.exists()){ idfile.delete(); }
*/
synchronized (MainActivity.class) {
MainActivity.threadcount++;
if (MainActivity.threadcount >= 5) {
for (int i = 1; i <= 5; i++) {
File deletefile = new File("/mnt/sdcard/" + i
+ ".txt");
deletefile.delete();
}
Message msg = new Message(); // anr
msg.what = DOWNLOAD_FINISH; // anr
handler.sendMessage(msg); // anr
}
}


} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值