写了一个多线程下载的demo分享一下:
<pre name="code" class="java">package com.example.administrator.demo;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Administrator on 2015/10/15.
*/
public class LoadDown implements DownThread.DownListener{
private int fileSize;
private int threadSize = 3;
private File saveFile;
public static final String TAG = "LoadDown";
public long startTime = 0;
/**
*判段sb卡状态
*
* @return
*/
public static boolean sdMounted() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
/**
*判断wifi是否开启
*
* @return
*/
public static boolean internetConnected(Context context) {
if (context != null) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (info != null) {
return info.isConnected();
}
}
return false;
}
/**
* 下载文件
* @param urlString 文件地址
* @param context 上下文
* @param downPath 要下载的路径
*/
public void dowmLoad(String urlString, Context context, String downPath) {
if (!sdMounted() || !internetConnected(context)) {
return;
}
File file = new File(downPath);
if (!file.exists()) {
file.mkdirs();
}
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5 * 1000);
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept-Language", "zh-CN");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.connect();
if (connection.getResponseCode() == 200) {
fileSize = connection.getContentLength();
connection.disconnect();
String fileName = urlString.substring(urlString.lastIndexOf("/"), urlString.length());
saveFile = new File(file, fileName);
int block = fileSize/threadSize;//每个线程要下载的部分
int offset = fileSize % threadSize;//多出的部分
for (int index = 0; index < threadSize; index ++){
if (index!=threadSize-1){
new DownThread(block*index,block,saveFile,url,index,this).start();
}else {
new DownThread(block*index,block+offset,saveFile,url,index,this).start();
}
}
startTime = System.currentTimeMillis();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onDown(int length, int id) {
}
private int count = 0;
@Override
public void onDownOver(int id) {
synchronized (this){
Log.i(TAG, id+"下载完成");
count++;
if (count==threadSize){
long time = System.currentTimeMillis();
Log.i(TAG,"结束时间"+time+"总共耗时"+(time-startTime));
}
}
}
}
package com.example.administrator.demo;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Administrator on 2015/10/15.
*/
public class DownThread extends Thread {
public static final String TAG = "DownThread";
private int start;//开始的字节
private int length;//要下的长度
private File saveFile;//要保存的文件
private URL downUrl;//下载链接
private int id;//线程id
private int downLength;//已经下载的字节
private DownListener listener;
public DownThread(int start, int length, File saveFile, URL downUrl, int id,DownListener listener) {
this.downUrl = downUrl;
this.saveFile = saveFile;
this.start = start;
this.length = length;
this.id = id;
this.listener = listener;
}
@Override
public void run() {
try {
HttpURLConnection connection = (HttpURLConnection) downUrl.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5 * 1000);
connection.setRequestProperty("Connection", "Keep-Alive");
int startPos = this.start;
int endPos = this.start + length;
connection.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos);//设置下载的字节的范围
InputStream is = connection.getInputStream();
byte[] buffer = new byte[1024];
int offset = -1;
int count = 0;
RandomAccessFile file = new RandomAccessFile(saveFile, "rwd");
file.seek(startPos);
while ((offset = is.read(buffer)) != -1) {
file.write(buffer, 0, offset);
downLength += offset;
if (listener!=null){
listener.onDown(downLength,id);
Log.i(TAG, "thread" + id + ":" + downLength + ":" + count++ + ":" + offset);
}
}
file.close();
is.close();
if (listener!=null) {
listener.onDownOver(id);
Log.i(TAG, id + "下载完成");
}
} catch (IOException e) {
e.printStackTrace();
}
super.run();
}
public interface DownListener{
void onDown(int length,int id);
void onDownOver(int id);
}
}