AsyncTask的3个泛型
• Param 传入数据类型
• Progress 更新UI数据类型
• Result 处理结果类型
AsyncTask的4个步骤
1、onPreExecute 执行前的操作
2、doInBackGround 后台执行的操作
3、onProgressUpdate 更新UI操作
4、onPostExecute 执行后的操作
/** * Created by lenovo on 2015/12/1. * 下载文件到本地,调用wps查看 */ public class ShowFileOnline extends AsyncTask<String, String, String> { Context context; MyFiles myFile; /** * 进度对话框 */ private ProgressDialog pdialog; public ShowFileOnline(Context context, MyFiles myFile) { this.context = context; this.myFile = myFile; /* 实例化进度条对话框 */ pdialog = new ProgressDialog(context); /* 进度条对话框属性设置 */ pdialog.setMessage("正在加载中..."); /* 进度值最大100 */ pdialog.setMax(100); /* 水平风格进度条 */ pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); /* 无限循环模式 */ pdialog.setIndeterminate(false); /* 可取消 */ pdialog.setCancelable(true); /* 显示对话框 */ pdialog.show(); } @Override protected String doInBackground( String... params) { /* FileDown down = new FileDown(); File file = down.downFile(UrlUtil.file + myFile.getVirtualPath(), PublicMethod.setFilePathInterim().getPath(), myFile.getFileName());*/ /* 所下载文件的URL */ try { URL url = new URL(UrlUtil.file + myFile.getVirtualPath()); File file=new File(PublicMethod.setFilePathInterim().getPath()+"/"+myFile.getFileName()); if(file.exists())return null; HttpURLConnection conn = (HttpURLConnection) url.openConnection(); /* URL属性设置 */ conn.setRequestMethod("POST"); /* URL建立连接 */ conn.connect(); /* 下载文件的大小 */ int fileOfLength = conn.getContentLength(); /* 每次下载的大小与总下载的大小 */ int totallength = 0; int length = 0; /* 输入流 */ InputStream in = conn.getInputStream(); /* 输出流 */ FileOutputStream out = new FileOutputStream(new File(PublicMethod.setFilePathInterim().getPath(), myFile.getFileName())); /* 缓存模式,下载文件 */ byte[] buff = new byte[1024 * 1024]; while ((length = in.read(buff)) > 0) { totallength += length; String str1 = ""+(int) ((totallength * 100) / fileOfLength); publishProgress(str1); out.write(buff, 0, length); } /* 关闭输入输出流 */ in.close(); out.flush(); out.close(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /* 预处理UI线程 */ @Override protected void onPreExecute() { pdialog.show(); super.onPreExecute(); } /* 结束时的UI线程 */ @Override protected void onPostExecute(String result) { //销毁对话框 pdialog.dismiss(); String path=PublicMethod.setFilePathInterim().getPath() + "/"+myFile.getFileName(); PublicMethod.openFile(path, context); super.onPostExecute(result); } /* 处理UI线程,会被多次调用,触发事件为publicProgress方法 */ /** * 此方法运行在主线程 * 借助此方法更新进度对话框中进度值 */ @Override protected void onProgressUpdate(String... values) { pdialog.setProgress(Integer.parseInt(values[0])); super.onProgressUpdate(values); } }