
package com.gaozewen.multidownloader;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private EditText mEt_thread_count;
private EditText mEt_path;
private LinearLayout mLl_container;
public String path = "http://192.168.1.102:8080/xunlei.exe";
public int totalThreadCount = 0;
public int runningThreadCount = 0;
private ArrayList<ProgressBar> mPbs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1. 找到控件
// 2. 在 button 点击事件中下载文件
// 3. 下载的时候显示下载进度
mEt_thread_count = (EditText) findViewById(R.id.et_thread_count);
mEt_path = (EditText) findViewById(R.id.et_path);
mLl_container = (LinearLayout) findViewById(R.id.ll_container);
}
/**
* 用第三方控件 xUtils 下载
* @param view
*/
public void download2(View view) {
path = mEt_path.getText().toString().trim();
HttpUtils http = new HttpUtils();
http.download(path, getCacheDir() + "/" + getDownloadFileName(path), true, new RequestCallBack<File>() {
@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
Toast.makeText(MainActivity.this,"下载成功", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(HttpException e, String s) {
Toast.makeText(MainActivity.this,"下载失败", Toast.LENGTH_SHORT).show();
}
@Override
public void onLoading(long total, long current, boolean isUploading) {
System.out.println(current);
super.onLoading(total, current, isUploading);
}
});
}
public void download(View view) {
totalThreadCount = Integer.valueOf(mEt_thread_count.getText().toString().trim());
path = mEt_path.getText().toString().trim();
mLl_container.removeAllViews();
mPbs = new ArrayList<>();
for (int i = 0; i < totalThreadCount; i++) {
// 有几个线程就创建几个 进度条
ProgressBar pb = (ProgressBar) View.inflate(this, R.layout.pb, null);
mLl_container.addView(pb);
mPbs.add(pb);
}
new Thread() {
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
int code = conn.getResponseCode();
if (code == 200) {
int length = conn.getContentLength();
System.out.println("file length: " + length);
// 创建一个空的文件,并且设置他的文件长度等于服务器上的文件长度
RandomAccessFile raf = new RandomAccessFile(getCacheDir() + "/" + getDownloadFileName(path), "rw");
raf.setLength(length);
raf.close();
int blockSize = length / totalThreadCount;
System.out.println("every block size: " + blockSize);
runningThreadCount = totalThreadCount;
for (int threadId = 0; threadId < totalThreadCount; threadId++) {
int startPosition = blockSize * threadId;
int endPosition = blockSize * (threadId + 1) - 1; // -1 是到当前块的最后一个字节
if (threadId == (totalThreadCount - 1)) {
endPosition = length - 1;
}
System.out.println(String.format("threadId: %s\ndownload rage: %s to %s", threadId, startPosition, endPosition));
new DownloadThread(threadId, startPosition, endPosition).start();
}
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
/**
* 从网路路径获取文件名
*
* @param path 网络路径
* @return 文件名
*/
private static String getDownloadFileName(String path) {
return path.substring(path.lastIndexOf("/") + 1);
}
/**
* 下载文件的线程
*/
private class DownloadThread extends Thread {
/**
* 线程 id
*/
private int threadId;
/**
* 当前线程下载的起始位置
*/
private int startPosition;
/**
* 当前线程下载的终止位置
*/
private int endPosition;
/**
* 当前线程需要去下载的总共的字节
*/
private int threadTotal;
/**
* 上次断点 下载的总共字节数
*/
private int lastDownloadTotalSize;
public DownloadThread(int threadId, int startPosition, int endPosition) {
this.threadId = threadId;
this.startPosition = startPosition;
this.endPosition = endPosition;
this.threadTotal = endPosition - startPosition;
mPbs.get(threadId).setMax(threadTotal); // 设置进度条
}
@Override
public void run() {
System.out.println(String.format("threadID: %s begin working", threadId));
// lest thread download it's self range data
try {
// 查询 记录断点信息的文件
File finfo = new File(getCacheDir(), totalThreadCount + getDownloadFileName(path) + threadId + ".txt");
if (finfo.exists() && finfo.length() > 0) { // 断点下载
FileInputStream fis = new FileInputStream(finfo);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String lastPosition = br.readLine();
int intLastPosition = Integer.parseInt(lastPosition);
// 进度条断点续借位置
lastDownloadTotalSize = intLastPosition - startPosition;
// This thread download data before times;
startPosition = intLastPosition;
fis.close();
}
// 第一次下载
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
System.out.println(String.format("begin and end: %s range of download: %s to %s", threadId, startPosition, endPosition));
conn.setRequestProperty("Range", String.format("bytes=%s-%s", startPosition, endPosition));
// 从服务器下载资源
int code = conn.getResponseCode();
if (code == 206) {
InputStream is = conn.getInputStream();
// 第一次没有这个文件则创建,下次直接打开这个文件
RandomAccessFile raf = new RandomAccessFile(getCacheDir() + "/" + getDownloadFileName(path), "rw");
// !!! position of begin to write
raf.seek(startPosition); // 将指针移动到这次开始续传的位置
byte[] buffer = new byte[1024];
int len = -1;
int total = 0; // 当前线程 这次下载的数据
while ((len = is.read(buffer)) != -1) {
raf.write(buffer, 0, len);
total += len;
// 创建记录 保存当前线程下载的位置 (注意: rwd 同步实时写入到设备中)
RandomAccessFile infoRaf = new RandomAccessFile(getCacheDir() + "/" + totalThreadCount + getDownloadFileName(path) + threadId + ".txt", "rwd");
infoRaf.write(String.valueOf(startPosition + total).getBytes());
infoRaf.close();
// 每次读写显示一个进度
mPbs.get(threadId).setProgress(total + lastDownloadTotalSize);
}
raf.close();
is.close();
System.out.println(String.format("thread: %s download complete...", threadId));
} else {
System.out.println("request download failed");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
synchronized (MainActivity.class) {
runningThreadCount--;
if (runningThreadCount <= 0) { // 多线程下载完成 删除 位置信息文件
System.out.println("multi thread download complete.");
for (int i = 0; i < totalThreadCount; i++) {
File positionFile = new File(getCacheDir(),totalThreadCount + getDownloadFileName(path) + i + ".txt");
// System.out.println(positionFile.delete());
}
}
}
}
}
}
}