Android(java)学习笔记216:多线程断点下载的原理(Android实现)

之前在Android(java)学习笔记215中,我们从JavaSE的角度去实现了多线程断点下载,下面从Android角度实现这个断点下载:

1. 新建一个Android工程:

(1)其中我们先实现布局文件activity_main.xml:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" > <EditText
android:id="@+id/et_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="http://192.168.1.100:8080/" /> <EditText
android:inputType="number"
android:id="@+id/et_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请设置下载线程的数量,默认3" /> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="download"
android:text="下载" /> <LinearLayout
android:paddingLeft="5dip"
android:paddingRight="5dip"
android:id="@+id/ll_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout> </LinearLayout>

布局效果如下:

Android(java)学习笔记216:多线程断点下载的原理(Android实现)

(2)其中的进度条样式pb.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:layout_height="wrap_content" />

2. MainActivity.java:

 package com.itheima.mutiledownloader;

 import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast; public class MainActivity extends Activity {
private EditText et_path;
private EditText et_count;
private LinearLayout ll_container;
private int threadCount = 3;
private String path;
protected int runningThreadCount; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_count = (EditText) findViewById(R.id.et_count);
et_path = (EditText) findViewById(R.id.et_path);
ll_container = (LinearLayout) findViewById(R.id.ll_container);
} public void download(View view){
String str_count = et_count.getText().toString().trim();
path = et_path.getText().toString().trim();
if(TextUtils.isEmpty(path)&&!path.startsWith("http://")){
Toast.makeText(this, "下载路径不合法", 0).show();
return;
}
if(!TextUtils.isEmpty(str_count)){
threadCount = Integer.parseInt(str_count);
}
ll_container.removeAllViews();
for(int i=0;i<threadCount;i++){
ProgressBar pb = (ProgressBar) View.inflate(this, R.layout.pb,null);
ll_container.addView(pb);
}
new Thread(){
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("服务器文件的大小为:"+length);
//创建一个空白文件文件的大小和服务器资源一样
RandomAccessFile raf = new RandomAccessFile(Environment.getExternalStorageDirectory().getPath()+"/"+getFileName(path), "rw");
raf.setLength(length);
raf.close();
//每个线程下载的平均区块大小
int blocksize = length / threadCount;
runningThreadCount = threadCount;
for(int threadId = 0;threadId<threadCount;threadId++){
int startIndex = threadId*blocksize;
int endIndex = (threadId+1)*blocksize-1;
if(threadId==(threadCount-1)){//最后一个线程的修正
endIndex = length - 1;
}
new DownloadThread(startIndex, endIndex, threadId).start();
}
}
} catch (Exception e) {
e.printStackTrace();
showToast("下载失败");
} };
}.start(); }
class DownloadThread extends Thread{
/**
* 理论上第一次开始的位置
*/
int firstStartIndex;
int startIndex;
int endIndex;
/**
* 当前线程下载到文件的位置
*/
int filePosition;
int threadId;
/**
* 当前线程需要下载的总文件大小
*/
int threadTotal;
ProgressBar pb;//当前线程对应的进度条
/**
*
* @param startIndex 开始位置
* @param endIndex 结束位置
* @param threadId 线程id
*/
public DownloadThread(int startIndex, int endIndex, int threadId) {
this.startIndex = startIndex;
this.firstStartIndex = startIndex;
this.endIndex = endIndex;
threadTotal = endIndex - startIndex;
this.threadId = threadId;
pb = (ProgressBar) ll_container.getChildAt(threadId);
pb.setMax(threadTotal);
filePosition = startIndex;
} @Override
public void run() {
//System.out.println("线程:"+threadId+"理论下载的位置:"+startIndex+"~~~"+endIndex);
//读取,看看有没有下载的历史数据,读下载的进度
try {
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/"+threadId+getFileName(path)+".txt");//用一个文本记录当前线程下载的进程
if(file.exists()&&file.length()>0){
FileInputStream fis = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
filePosition = Integer.parseInt(br.readLine());//上一次下载到文件的哪个位子。
startIndex = filePosition;
fis.close();
}
System.out.println("线程:"+threadId+"实际上下载的位置:"+startIndex+"~~~"+endIndex);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
int code = conn.getResponseCode();//2XX 成功 3XX重定向 4XX资源找不到 5XX服务器异常
if(code == 206){
InputStream is = conn.getInputStream();
RandomAccessFile raf = new RandomAccessFile(Environment.getExternalStorageDirectory().getPath()+"/"+getFileName(path), "rwd");
//一定要记得定位文件写的位置
raf.seek(startIndex);
byte[] buffer = new byte[1024*4];//缓冲区的大小
int len = -1;
while((len = is.read(buffer))!=-1){
raf.write(buffer, 0, len);
filePosition+=len;//记录写入数据的进度
int process = filePosition - firstStartIndex;
pb.setProgress(process);
RandomAccessFile rafinfo = new RandomAccessFile(file, "rwd");
rafinfo.write(String.valueOf(filePosition).getBytes());
rafinfo.close();
}
raf.close();
is.close();
System.out.println("线程:"+threadId+"下载完毕了。");
synchronized (MainActivity.this) {//加锁,同步运行,保证下面一段代码在同一个时间片运行,原子性执行
runningThreadCount--;
if(runningThreadCount==0){
System.out.println("所有的线程都下载完毕了");
showToast("下载完毕了");
for(int i =0;i<threadCount;i++){
File f = new File(Environment.getExternalStorageDirectory().getPath()+"/"+i+getFileName(path)+".txt");
System.out.println(f.delete());
}
}
} }
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 获取路径对应的文件名
* @param path
* @return
*/
private static String getFileName(String path){
int beginIndex = path.lastIndexOf("/")+1;
return path.substring(beginIndex);
} private void showToast(final String text){
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, text, 0).show();
}
});
}
}

3. 其中AndroidMainfest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.itheima.mutiledownloader"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.itheima.mutiledownloader.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>

 

上一篇:安装php后无法动态加载库


下一篇:33、多线程断点下载的实现&界面的更新