Android学习 --有进度条下载对话框

好吧 这是人人的一个面试 很简单 但是当时没做过 没办法 不会就是不会 

package cn.itcast.mobilesafe.engine;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ProgressDialog;

public class DownLoadFileTask {
	
	/**
	 * 
	 * @param path 服务器文件路径
	 * @param filepath 本地文件路径 
	 * @param pd 传入dialog
	 * @return 本地文件对象
	 * @throws Exception
	 */
	public static File getFile(String path,String filepath,ProgressDialog pd) throws Exception{
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5000);
		if(conn.getResponseCode() == 200){
			int total =  conn.getContentLength();
			pd.setMax(total);
			InputStream is = conn.getInputStream();
			File file = new File(filepath);
			FileOutputStream fos = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int len = 0;
			int process = 0;
			while((len = is.read(buffer))!=-1){
				fos.write(buffer, 0, len);
				process +=len;
				pd.setProgress(process);
				Thread.sleep(50);
			}
			fos.flush();
			fos.close();
			is.close();
			
			return file;
		}
		return null;
	}
}

private class DownLoadFileThreadTask implements Runnable {
		private String path; // 服务器路径
		private String filepath; // 本地文件路径

		public DownLoadFileThreadTask(String path, String filepath) {
			this.path = path;
			this.filepath = filepath;
		}

		public void run() {
			try {
				File file = DownLoadFileTask.getFile(path, filepath,pd);
				Log.i(TAG,"下载成功");
				pd.dismiss();
				install(file);
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(getApplicationContext(), "下载文件失败", 0).show();
				pd.dismiss();
				loadMainUI();
				
			}

		}

	}

启动下载

DownLoadFileThreadTask task = new DownLoadFileThreadTask(info.getApkurl(), "/sdcard/new.apk");
					pd.show();
					new Thread(task).start();


posted @ 2012-12-05 21:07  sfshine  阅读(432)  评论(0编辑  收藏  举报