package com.itheima.multithreaddownload;
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 android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.app.Activity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
String path = "http://169.254.244.136:8080/QQPlayer.exe";
int threadCount = 3;
int finishedThread = 0;
int downloadProgress = 0;
private ProgressBar pb;
private TextView tv;
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
tv.setText((long)pb.getProgress() * 100 / pb.getMax() + "%");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pb = (ProgressBar) findViewById(R.id.pb);
tv = (TextView) findViewById(R.id.tv);
}
public void click(View v){
Thread t = new Thread(){
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
if(conn.getResponseCode() == 200){
int length = conn.getContentLength();
File file = new File(Environment.getExternalStorageDirectory(), getNameFromPath(path));
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.setLength(length);
raf.close();
pb.setMax(length);
int size = length / threadCount;
for (int id = 0; id < threadCount; id++) {
int startIndex = id * size;
int endIndex = (id + 1) * size - 1;
if(id == threadCount - 1){
endIndex = length - 1;
}
System.out.println("线程" + id + "下载的区间:" + startIndex + " ~ " + endIndex);
new DownLoadThread(id, startIndex, endIndex).start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
public String getNameFromPath(String path){
int index = path.lastIndexOf("/");
return path.substring(index + 1);
}
class DownLoadThread extends Thread{
int threadId;
int startIndex;
int endIndex;
public DownLoadThread(int threadId, int startIndex, int endIndex) {
super();
this.threadId = threadId;
this.startIndex = startIndex;
this.endIndex = endIndex;
}
@Override
public void run() {
try {
File fileProgress = new File(Environment.getExternalStorageDirectory(), threadId + ".txt");
int lastProgress = 0;
if(fileProgress.exists()){
FileInputStream fis = new FileInputStream(fileProgress);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
lastProgress = Integer.parseInt(br.readLine());
startIndex += lastProgress;
fis.close();
downloadProgress += lastProgress;
pb.setProgress(downloadProgress);
handler.sendEmptyMessage(1);
}
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
conn.setRequestProperty("Range", "bytes=" + startIndex + "-" + endIndex);
if(conn.getResponseCode() == 206){
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
int len = 0;
int total = lastProgress;
File file = new File(Environment.getExternalStorageDirectory(), getNameFromPath(path));
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
raf.seek(startIndex);
while((len = is.read(b)) != -1){
raf.write(b, 0, len);
total += len;
System.out.println("线程" + threadId + "下载了:" + total);
RandomAccessFile rafProgress = new RandomAccessFile(fileProgress, "rwd");
rafProgress.write((total + "").getBytes());
rafProgress.close();
downloadProgress += len;
pb.setProgress(downloadProgress);
handler.sendEmptyMessage(1);
}
raf.close();
System.out.println("线程" + threadId + "下载完毕------------------");
finishedThread++;
synchronized (path) {
if(finishedThread == threadCount){
for (int i = 0; i < threadCount; i++) {
File f = new File(Environment.getExternalStorageDirectory(), i + ".txt");
f.delete();
}
finishedThread = 0;
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
<?xml version="1.0"?>
-<LinearLayout android:orientation="vertical" tools:context=".MainActivity" android:paddingTop="@dimen/activity_vertical_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:layout_height="match_parent" android:layout_width="match_parent" xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android">
<Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:onClick="click" android:text="下载"/>
<ProgressBar android:layout_height="wrap_content" android:layout_width="match_parent" android:id="@+id/pb" style="@android:style/Widget.ProgressBar.Horizontal"/>
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="0%" android:id="@+id/tv" android:layout_gravity="right"/>
</LinearLayout>
<?xml version="1.0" encoding="UTF-8"?>
-<manifest android:versionName="1.0" android:versionCode="1" package="com.itheima.multithreaddownload" xmlns:android="http://schemas.android.com/apk/res/android">
<uses-sdk android:targetSdkVersion="17" android:minSdkVersion="8"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
-<application android:theme="@style/AppTheme" android:label="@string/app_name" android:icon="@drawable/ic_launcher" android:allowBackup="true">
-<activity android:name="com.itheima.multithreaddownload.MainActivity" android:label="@string/app_name">
-<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>