依赖
compile 'com.loopj.android:android-async-http:1.4.9'
Activity
public class OtherActivity extends AppCompatActivity {
protected static final String TAG = "OtherActivity";
private final static int threadsize = 3;
protected static final int SET_MAX = 0;
public static final int UPDATE_VIEW = 1;
private ProgressBar pb;
private Button bt_download;
private Button bt_pause;
private TextView tv_info;
private Handler mHandler = new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SET_MAX:
int filelength = msg.arg1;
pb.setMax(filelength);
break;
case UPDATE_VIEW:
int len = msg.arg1;
pb.setProgress(pb.getProgress()+len);
int max = pb.getMax();
int progress = pb.getProgress();
int result = (progress*100)/max;
tv_info.setText("下载:"+result+"%");
break;
default:
break;
}
};
};
String uri = "http://c.hiphotos.baidu.com/image/pic/item/b90e7bec54e736d1e51217c292504fc2d46269f3.jpg";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
pb = (ProgressBar) findViewById(R.id.pb);
tv_info = (TextView) findViewById(R.id.tv_info);
bt_download = (Button) findViewById(R.id.bt_download);
bt_pause = (Button) findViewById(R.id.bt_pause);
String name = getFileName(uri);
File file = new File(Environment.getExternalStorageDirectory(), name);
if (file.exists()){
int filelength = (int) file.length();
pb.setMax(filelength);
try {
int count = 0;
for (int threadid = 0; threadid < threadsize; threadid++) {
int existDownloadLength = readDownloadInfo(threadid);
count = count + existDownloadLength;
}
pb.setProgress(count);
int result = (count * 100) / filelength;
tv_info.setText("下载:" + result + "%");
} catch (Exception e) {
e.printStackTrace();
}
}
}
private boolean flag = false;
public void pause(View v){
flag = false;
bt_download.setEnabled(true);
bt_pause.setEnabled(false);
}
public void download(View v){
flag = true;
bt_download.setEnabled(false);
bt_pause.setEnabled(true);
new Thread(){
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpHead request = new HttpHead(uri);
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode() == 200){
Header[] headers = response.getHeaders("Content-Length");
String value = headers[0].getValue();
int filelength = Integer.parseInt(value);
Log.i(TAG, "filelength:"+filelength);
Message msg_setmax = Message.obtain(mHandler, SET_MAX, filelength, 0);
msg_setmax.sendToTarget();
for(int threadid=0;threadid<threadsize;threadid++){
File file = new File(Environment.getExternalStorageDirectory(),threadid+".txt");
if(!file.exists()){
file.createNewFile();
}
}
String name = getFileName(uri);
File file = new File(Environment.getExternalStorageDirectory(),name);
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.setLength(filelength);
raf.close();
int block = (filelength%threadsize == 0)?(filelength/threadsize):(filelength/threadsize+1);
for(int threadid=0;threadid<threadsize;threadid++){
new DownloadThread(threadid, uri, file, block).start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
private class DownloadThread extends Thread{
private int threadid;
private String uri;
private File file;
private int block;
private int start;
private int end;
public DownloadThread(int threadid, String uri, File file, int block) {
super();
this.threadid = threadid;
this.uri = uri;
this.file = file;
this.block = block;
start = threadid * block;
end = (threadid + 1)*block -1;
try {
int existDownloadLength = readDownloadInfo(threadid);
start = start + existDownloadLength;
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
super.run();
try {
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.seek(start);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(uri);
request.addHeader("Range", "bytes:"+start+"-"+end);
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode() == 200){
InputStream inputStream = response.getEntity().getContent();
byte[] buffer = new byte[1024];
int len = 0;
while((len = inputStream.read(buffer)) != -1){
if(!flag){
return;
}
raf.write(buffer, 0, len);
int existDownloadLength = readDownloadInfo(threadid);
int newDownloadLength = existDownloadLength + len;
updateDownloadInfo(threadid, newDownloadLength);
Message update_msg = Message.obtain(mHandler, UPDATE_VIEW, len, 0);
update_msg.sendToTarget();
SystemClock.sleep(50);
}
inputStream.close();
raf.close();
Log.i(TAG, "第"+threadid+"条线程下载完成");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 读取指定线程的下载数据量
* @param threadid 线程的id
* @return
* @throws Exception
*/
public int readDownloadInfo(int threadid) throws Exception{
File file = new File(Environment.getExternalStorageDirectory(),threadid+".txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String content = br.readLine();
int downlength = 0;
if(!TextUtils.isEmpty(content)){
downlength = Integer.parseInt(content);
}
br.close();
return downlength;
}
/**
* 更新下载记录
* @param threadid
* @param newDownloadLength
*/
public void updateDownloadInfo(int threadid,int newDownloadLength) throws Exception{
File file = new File(Environment.getExternalStorageDirectory(),threadid+".txt");
FileWriter fw = new FileWriter(file);
fw.write(newDownloadLength+"");
fw.close();
}
/**
* 获取文件的名称
* @param uri
* @return
*/
private String getFileName(String uri){
return uri.substring(uri.lastIndexOf("/")+1);
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main"
android:layout_width="match_parent" android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.lv.mama.myapplication.MainActivity">
<ProgressBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Horizontal"
android:id="@+id/bar"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始"
android:id="@+id/start"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="结束"
android:id="@+id/end"/>
</LinearLayout>
</LinearLayout>