public class FileDownloadHelper {
private static final String TAG = "FileDownloadHelper";
/** 线程池 */
private ThreadPool mPool = new ThreadPool();
/** 开始下载 */
public static final int MESSAGE_START = 0;
/** 更新进度 */
public static final int MESSAGE_PROGRESS = 1;
/** 下载结束 */
public static final int MESSAGE_STOP = 2;
/** 下载出错 */
public static final int MESSAGE_ERROR = 3;
/** 中途终止 */
private volatile boolean mIsStop = false;
private Handler mHandler;
public volatile HashMap<String, String> mDownloadUrls = new HashMap<String, String>();
public FileDownloadHelper(Handler handler) {
if (handler == null)
throw new IllegalArgumentException("handler不能为空!");
this.mHandler = handler;
}
public void stopALl() {
mIsStop = true;
mPool.stop();
}
/**
* 下载一个新的文件
*
* @param url
* @param savePath
*/
public void newDownloadFile(final String url, final String savePath) {
if (mDownloadUrls.containsKey(url))
return;
else
mDownloadUrls.put(url, savePath);
mPool.start(new Runnable() {
@Override
public void run() {
mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_START, url));
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
final int size = (int) entity.getContentLength();
inputStream = entity.getContent();
if (size > 0 && inputStream != null) {
outputStream = new FileOutputStream(savePath);
int ch = -1;
byte[] buf = new byte[1024];
// 每秒更新一次进度
new Timer().schedule(new TimerTask() {
@Override
public void run() {
try {
FileInputStream fis = new FileInputStream(new File(savePath));
int downloadedSize = fis.available();
if (downloadedSize >= size)
cancel();
mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_PROGRESS, downloadedSize, size, url));
} catch (Exception e) {
}
}
}, 50, 1000);
while ((ch = inputStream.read(buf)) != -1 && !mIsStop) {
outputStream.write(buf, 0, ch);
}
outputStream.flush();
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ERROR,
url + ":" + e.getMessage()));
} finally {
try {
if (outputStream != null)
outputStream.close();
} catch (IOException ex) {
}
try {
if (inputStream != null)
inputStream.close();
} catch (IOException ex) {
}
}
mDownloadUrls.remove(url);
mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_STOP, url));
}
});
}
}
ThreadPool.java
package com.example.c.myutils;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import android.os.Build;
public class ThreadPool {
private AtomicBoolean mStopped = new AtomicBoolean(Boolean.FALSE);
private ThreadPoolExecutor mQueue;
public ThreadPool() {
if (Build.VERSION.SDK_INT > 8) {
mQueue = new ThreadPoolExecutor(10, 10, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(), sThreadFactory);
mQueue.allowCoreThreadTimeOut(true);
} else {
mQueue = new ThreadPoolExecutor(2, 10, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(), sThreadFactory);
}
}
public void start(Runnable run) {
mQueue.execute(run);
}
public void stop() {
if (!mStopped.get()) {
mQueue.shutdownNow();
mStopped.set(Boolean.TRUE);
}
}
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "ThreadPool #" + mCount.getAndIncrement());
}
};
}
下面贴出用法:
private FileDownloadHelper mDownloadHelper;
private MyHandler myHandler;
/**
*
* @Description:TODO
*/
private void XiaZaiWenJian() {
// TODO Auto-generated method stub
myHandler = new MyHandler();
mDownloadHelper = new FileDownloadHelper(myHandler);
mDownloadHelper.newDownloadFile("http://172.16.2.137:8080/myweb/video/1.3gp", SPConstant.SDcard_PATH+"/"+"aa.3gp");
}
public class MyHandler extends Handler{
/**
* Title: handleMessage
* @Description:
* @param msg
* @see android.os.Handler#handleMessage(android.os.Message)
*/
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case FileDownloadHelper.MESSAGE_START:
LogUtile.d(TAG, "开始下载");
break;
case FileDownloadHelper.MESSAGE_PROGRESS:
int dangQian = msg.arg1;
int total = msg.arg2;
if (dangQian < total) {
LogUtile.d(TAG, "当前下载的进度"+dangQian+"文件总长度"+total);
}
break;
case FileDownloadHelper.MESSAGE_STOP:
LogUtile.d(TAG, "结束下载");
break;
case FileDownloadHelper.MESSAGE_ERROR:
LogUtile.d(TAG, "下载出错");
break;
default:
break;
}
}
}