今天看到大神写的相关详解Android中AsyncTask的使用 ,真的很是佩服,下面我将学习到的AsynTask知识运用到项目中,其中也涉及一些文件的下载与存储到本地
啥都不说了,直接上代码,我将对其进行详细解说,哈哈哈哈哈哈
1 public class DownloadAsyncTask extends AsyncTask<String, Float, Integer> { 2 3 // private static final String TAG = "DownloadAsyncTask"; 4 5 /****** 下载正常 ******/ 6 private static final int CORRECT = 0; 7 /****** 404未找到资源 ******/ 8 private static final int NOT_FOUND = 1; 9 /****** 下载异常 ******/ 10 private static final int ERROR = 2; 11 /****** 取消下载 ******/ 12 private static final int CANCEL = 3; 13 /****** SD异常 ******/ 14 private static final int SD_ERROR = 4; 15 16 private DownloadListener mDownloadListener; 17 private String mUrl; 18 private File tempFile; 19 20 public interface DownloadListener { 21 22 public void onDownloading(float progress); 23 24 public void onDownloadComplete(String path); 25 26 public void onDownloadError(String msg); 27 28 public void onDownload404(); 29 30 } 31 32 public DownloadAsyncTask(String url) { 33 mUrl = url.replace("-", "%2D"); 34 mUrl = mUrl.replace(" ", "%20"); 35 mUrl = mUrl.replace("+", "%2B"); 36 } 37 /** 38 * 获取下载文件 39 * @param filename 40 * @return 41 */ 42 public static File getDownloadFile(String filename) { 43 String downloadDir = Environment.getExternalStorageDirectory() 44 .getAbsolutePath() +"/Hbdownload"; 45 File dir = new File(downloadDir); 46 if (!dir.exists()) { 47 dir.mkdirs(); 48 } 49 return new File(dir, filename); 50 } 51 /** 52 * 创建下载文件 53 * @param filename 54 */ 55 public static File createDownloadFile(String filename) throws Exception { 56 String downloadDir = Environment.getExternalStorageDirectory() 57 .getAbsolutePath() + "/Hbdownload"; 58 File dir = new File(downloadDir); 59 return createFile(dir, filename); 60 } 61 // 在指定SD目录创建文件 62 private static File createFile(File dir, String filename) throws Exception { 63 if (!dir.exists()) { 64 dir.mkdirs(); 65 } 66 File file = new File(dir, filename); 67 file.createNewFile(); 68 return file; 69 } 70 /** 71 * 创建上传文件 72 * @return 73 */ 74 public static File createUploadFile(String filename) throws Exception { 75 String uploadDir = Environment.getExternalStorageDirectory() 76 .getAbsolutePath() +"/Hbdownload"; 77 File dir = new File(uploadDir); 78 return createFile(dir, filename); 79 } 80 @Override 81 protected Integer doInBackground(String... params) { 82 tempFile = getDownloadFile(params[0]); 83 if (tempFile.exists()) return CORRECT; 84 try { 85 tempFile =createDownloadFile(params[0]); 86 } catch (Exception e) { 87 e.printStackTrace(); 88 return SD_ERROR; 89 } 90 FileOutputStream fos = null; 91 InputStream istream = null; 92 try { 93 HttpClient httpClient = new DefaultHttpClient(); 94 HttpGet get = new HttpGet(mUrl); 95 HttpResponse response = httpClient.execute(get); 96 int statusCode = response.getStatusLine().getStatusCode(); 97 if (statusCode == HttpStatus.SC_OK) { 98 istream = response.getEntity().getContent(); 99 100 fos = new FileOutputStream(tempFile); 101 long total = response.getEntity().getContentLength(); 102 int readTotal = 0; 103 byte[] buffer = new byte[1024 * 10]; 104 int length; 105 while ((length = istream.read(buffer)) > -1) { 106 if (isCancelled()) { 107 return CANCEL; 108 } 109 fos.write(buffer, 0, length); 110 readTotal += length; 111 float progress = readTotal / (total * 1.0f) * 100; 112 publishProgress(progress); 113 } 114 fos.flush(); 115 return CORRECT; 116 } 117 if (statusCode == HttpStatus.SC_NOT_FOUND) { 118 return NOT_FOUND; 119 } 120 return ERROR; 121 } catch (Exception e) { 122 e.printStackTrace(); 123 } finally { 124 if (fos != null) { 125 try { 126 fos.close(); 127 } catch (IOException e) { 128 e.printStackTrace(); 129 } 130 } 131 if (istream != null) { 132 try { 133 istream.close(); 134 } catch (IOException e) { 135 e.printStackTrace(); 136 } 137 } 138 } 139 return ERROR; 140 } 141 142 @Override 143 protected void onProgressUpdate(Float... values) { 144 super.onProgressUpdate(values); 145 if (mDownloadListener != null) { 146 mDownloadListener.onDownloading(values[0]); 147 } 148 } 149 150 151 @Override 152 protected void onPostExecute(Integer result) { 153 super.onPostExecute(result); 154 if (mDownloadListener != null) { 155 switch (result) { 156 case CORRECT: 157 mDownloadListener.onDownloadComplete(tempFile.getAbsolutePath()); 158 break; 159 case NOT_FOUND: 160 mDownloadListener.onDownload404(); 161 tempFile.delete(); 162 break; 163 case ERROR: 164 mDownloadListener.onDownloadError("文件预览出现异常"); 165 tempFile.delete(); 166 break; 167 case SD_ERROR: 168 mDownloadListener.onDownloadError("SD卡出现异常,请检查您的设备上是否有SD卡"); 169 tempFile.delete(); 170 case CANCEL: 171 tempFile.delete(); 172 break; 173 } 174 } 175 } 176 177 public void setDownloadListener (DownloadListener listener) { 178 mDownloadListener = listener; 179 } 180 181 }
首先在使用DownloadAsyncTask时只需要几个步骤即可
1 DownloadAsyncTask task = new DownloadAsyncTask(url); 2 task.setDownloadListener(new DownloadAsyncTask.DownloadListener() { 3 4 @Override 5 public void onDownloading(float progress) { 6 7 } 8 9 @Override 10 public void onDownloadComplete(String path) { 11 ((BaseAppActivity) context).dismissLoadingDialog(); 12 activity.runOnUiThread(new Runnable() { 13 public void run() { 14 15 } 16 });
//下面是成功后的一些步骤 17 try { 18 if (PPT.contains(type)) { 19 activity.startActivity(FileShowUtils.getPptFileIntent(path)); 20 } else if (WORD.contains(type)) { 21 activity.startActivity(FileShowUtils.getWordFileIntent(path)); 22 } else if (EXCEL.contains(type)) { 23 activity.startActivity(FileShowUtils.getExcelFileIntent(path)); 24 } else if (TEXT.contains(type)) { 25 activity.startActivity(FileShowUtils.getTextFileIntent(path)); 26 } else if (PDF.contains(type)) { 27 activity.startActivity(FileShowUtils.getPdfFileIntent(path)); 28 } else if (ZIP.contains(type)) { 29 30 } else if (IMAGE.contains(type)) { 31 activity.startActivity(FileShowUtils.getImageFileIntent(path)); 32 } else if (AUDIO.contains(type)) { 33 activity.startActivity(FileShowUtils.getAudioFileIntent(path)); 34 } else if (VIDEO.contains(type)) { 35 activity.startActivity(FileShowUtils.getVideoFileIntent(path)); 36 } else { 37 ((BaseAppActivity) context).showCustomToast("暂时不支持此格式文件的预览"); 38 } 39 40 41 } catch (Exception e) { 42 ((BaseAppActivity) context).showCustomToast("您的设备上没有可以打开此类文件的应用"); 43 } 44 45 46 } 47 48 @Override 49 public void onDownloadError(String msg) { 50 ((BaseAppActivity) context).dismissLoadingDialog(); 51 ((BaseAppActivity) context).showCustomToast("未知错误"); 52 } 53 54 @Override 55 public void onDownload404() { 56 ((BaseAppActivity) context).dismissLoadingDialog(); 57 ((BaseAppActivity) context).showCustomToast("未知错误"); 58 } 59 }); 60 task.execute(filename);
AsyncTask在使用之前首先调用execute(Params... params),执行一个异步任务,需要我们在代码中调用此方法,触发异步任务的执行。
在DownloadAsyncTask 中我们继承AsyncTask,那么我们将在doInBackground方法中执行较为费时的操作,此方法将接收输入参数和返回计算结果,我们在doinBackground方法中,首先获取下载文件,
如果我们获取的文件在本地存在,那么表示我们的文件本地存在那么就不需要下载,我们可以返回正常的状态,之后我们可以直接使用,如果不存在,则需要我们创建下载文件,将文件通过文件流读写存储到我们建立的文件夹下,成功后则返回状态为正常,在其中过程中我们如果发现不可建立文件等情况则返回sd卡错误的状态,之后我们就可以调用AsyncTask的publishProgress(Progress... values)来更新进度信息
同时调用onProgressUpdate(Progress... values),在调用publishProgress(Progress... values)时,此方法被执行,直接将进度信息更新到UI组件上,最后调用onPostExecute(Result result)方法,对于返回的状态进行操作,在我写的这个DownloadAsyncTask中我使用了接口进行回调,我们可以在回调中进行相关操作,就介绍到这里了,其中代码是参照大神写的,我看过之后感觉很是佩服,因此将自己的一些认知告诉大家,希望大家喜欢!
注意:
在使用的时候,有几点需要格外注意:
1.异步任务的实例必须在UI线程中创建。
2.execute(Params... params)方法必须在UI线程中调用。
3.不要手动调用onPreExecute(),doInBackground(Params... params),onProgressUpdate(Progress... values),onPostExecute(Result result)这几个方法。
4.不能在doInBackground(Params... params)中更改UI组件的信息。
5.一个任务实例只能执行一次,如果执行第二次将会抛出异常。