【No2.】下载文件工具类

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;
			}
		}
	}



 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值