云炬Android开发笔记 5-8文件下载功能设计与实现

5.文件下载功能设计与实现

【说明】比较复杂;

【增加参数】

 云炬Android开发笔记 5-8文件下载功能设计与实现

云炬Android开发笔记 5-8文件下载功能设计与实现

云炬Android开发笔记 5-8文件下载功能设计与实现

云炬Android开发笔记 5-8文件下载功能设计与实现

【新建downloadhandler】新建下载处理类;

云炬Android开发笔记 5-8文件下载功能设计与实现

云炬Android开发笔记 5-8文件下载功能设计与实现

【使用异步的下载方法】

云炬Android开发笔记 5-8文件下载功能设计与实现

云炬Android开发笔记 5-8文件下载功能设计与实现

【file工具类】没有讲解,课下编写的

  1 package com.flj.latte.util.file;
  2 
  3 import android.content.ContentResolver;
  4 import android.content.Context;
  5 import android.content.Intent;
  6 import android.content.res.AssetManager;
  7 import android.database.Cursor;
  8 import android.graphics.Bitmap;
  9 import android.graphics.Typeface;
 10 import android.media.MediaScannerConnection;
 11 import android.net.Uri;
 12 import android.os.Build;
 13 import android.os.Environment;
 14 import android.provider.MediaStore;
 15 import android.webkit.MimeTypeMap;
 16 import android.widget.TextView;
 17 
 18 import com.flj.latte.app.Latte;
 19 
 20 import java.io.BufferedInputStream;
 21 import java.io.BufferedOutputStream;
 22 import java.io.BufferedReader;
 23 import java.io.File;
 24 import java.io.FileNotFoundException;
 25 import java.io.FileOutputStream;
 26 import java.io.IOException;
 27 import java.io.InputStream;
 28 import java.io.InputStreamReader;
 29 import java.text.SimpleDateFormat;
 30 import java.util.Date;
 31 import java.util.Locale;
 32 
 33 
 34 public final class FileUtil {
 35 
 36     //格式化的模板
 37     private static final String TIME_FORMAT = "_yyyyMMdd_HHmmss";
 38 
 39     private static final String SDCARD_DIR =
 40             Environment.getExternalStorageDirectory().getPath();
 41 
 42     //默认本地上传图片目录
 43     public static final String UPLOAD_PHOTO_DIR =
 44             Environment.getExternalStorageDirectory().getPath() + "/a_upload_photos/";
 45 
 46     //网页缓存地址
 47     public static final String WEB_CACHE_DIR =
 48             Environment.getExternalStorageDirectory().getPath() + "/app_web_cache/";
 49 
 50     //系统相机目录
 51     public static final String CAMERA_PHOTO_DIR =
 52             Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath() + "/Camera/";
 53 
 54     private static String getTimeFormatName(String timeFormatHeader) {
 55         final Date date = new Date(System.currentTimeMillis());
 56         //必须要加上单引号
 57         final SimpleDateFormat dateFormat = new SimpleDateFormat("'" + timeFormatHeader + "'" + TIME_FORMAT, Locale.getDefault());
 58         return dateFormat.format(date);
 59     }
 60 
 61     /**
 62      * @param timeFormatHeader 格式化的头(除去时间部分)
 63      * @param extension        后缀名
 64      * @return 返回时间格式化后的文件名
 65      */
 66     public static String getFileNameByTime(String timeFormatHeader, String extension) {
 67         return getTimeFormatName(timeFormatHeader) + "." + extension;
 68     }
 69 
 70     @SuppressWarnings("ResultOfMethodCallIgnored")
 71     private static File createDir(String sdcardDirName) {
 72         //拼接成SD卡中完整的dir
 73         final String dir = SDCARD_DIR + "/" + sdcardDirName + "/";
 74         final File fileDir = new File(dir);
 75         if (!fileDir.exists()) {
 76             fileDir.mkdirs();
 77         }
 78         return fileDir;
 79     }
 80 
 81     @SuppressWarnings("ResultOfMethodCallIgnored")
 82     public static File createFile(String sdcardDirName, String fileName) {
 83         return new File(createDir(sdcardDirName), fileName);
 84     }
 85 
 86     private static File createFileByTime(String sdcardDirName, String timeFormatHeader, String extension) {
 87         final String fileName = getFileNameByTime(timeFormatHeader, extension);
 88         return createFile(sdcardDirName, fileName);
 89     }
 90 
 91     //获取文件的MIME
 92     public static String getMimeType(String filePath) {
 93         final String extension = getExtension(filePath);
 94         return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
 95     }
 96 
 97     //获取文件的后缀名
 98     public static String getExtension(String filePath) {
 99         String suffix = "";
100         final File file = new File(filePath);
101         final String name = file.getName();
102         final int idx = name.lastIndexOf('.');
103         if (idx > 0) {
104             suffix = name.substring(idx + 1);
105         }
106         return suffix;
107     }
108 
109     /**
110      * 保存Bitmap到SD卡中
111      *
112      * @param dir      目录名,只需要写自己的相对目录名即可
113      * @param compress 压缩比例 100是不压缩,值约小压缩率越高
114      * @return 返回该文件
115      */
116     public static File saveBitmap(Bitmap mBitmap, String dir, int compress) {
117 
118         final String sdStatus = Environment.getExternalStorageState();
119         // 检测sd是否可用
120         if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
121             return null;
122         }
123         FileOutputStream fos = null;
124         BufferedOutputStream bos = null;
125         File fileName = createFileByTime(dir, "DOWN_LOAD", "jpg");
126         try {
127             fos = new FileOutputStream(fileName);
128             bos = new BufferedOutputStream(fos);
129             mBitmap.compress(Bitmap.CompressFormat.JPEG, compress, bos);// 把数据写入文件
130         } catch (FileNotFoundException e) {
131             e.printStackTrace();
132         } finally {
133             try {
134 
135                 if (bos != null) {
136                     bos.flush();
137                 }
138                 if (bos != null) {
139                     bos.close();
140                 }
141                 //关闭流
142                 if (fos != null) {
143                     fos.flush();
144                 }
145                 if (fos != null) {
146                     fos.close();
147                 }
148             } catch (IOException e) {
149                 e.printStackTrace();
150             }
151         }
152         refreshDCIM();
153 
154         return fileName;
155     }
156 
157     public static File writeToDisk(InputStream is, String dir, String name) {
158         final File file = FileUtil.createFile(dir, name);
159         BufferedInputStream bis = null;
160         FileOutputStream fos = null;
161         BufferedOutputStream bos = null;
162 
163         try {
164             bis = new BufferedInputStream(is);
165             fos = new FileOutputStream(file);
166             bos = new BufferedOutputStream(fos);
167 
168             byte data[] = new byte[1024 * 4];
169 
170             int count;
171             while ((count = bis.read(data)) != -1) {
172                 bos.write(data, 0, count);
173             }
174 
175             bos.flush();
176             fos.flush();
177 
178 
179         } catch (IOException e) {
180             e.printStackTrace();
181         } finally {
182             try {
183                 if (bos != null) {
184                     bos.close();
185                 }
186                 if (fos != null) {
187                     fos.close();
188                 }
189                 if (bis != null) {
190                     bis.close();
191                 }
192                 is.close();
193             } catch (IOException e) {
194                 e.printStackTrace();
195             }
196         }
197 
198         return file;
199     }
200 
201     public static File writeToDisk(InputStream is, String dir, String prefix, String extension) {
202         final File file = FileUtil.createFileByTime(dir, prefix, extension);
203         BufferedInputStream bis = null;
204         FileOutputStream fos = null;
205         BufferedOutputStream bos = null;
206 
207         try {
208             bis = new BufferedInputStream(is);
209             fos = new FileOutputStream(file);
210             bos = new BufferedOutputStream(fos);
211 
212             byte data[] = new byte[1024 * 4];
213 
214             int count;
215             while ((count = bis.read(data)) != -1) {
216                 bos.write(data, 0, count);
217             }
218 
219             bos.flush();
220             fos.flush();
221 
222 
223         } catch (IOException e) {
224             e.printStackTrace();
225         } finally {
226             try {
227                 if (bos != null) {
228                     bos.close();
229                 }
230                 if (fos != null) {
231                     fos.close();
232                 }
233                 if (bis != null) {
234                     bis.close();
235                 }
236                 is.close();
237             } catch (IOException e) {
238                 e.printStackTrace();
239             }
240         }
241 
242         return file;
243     }
244 
245     /**
246      * 通知系统刷新系统相册,使照片展现出来
247      */
248     private static void refreshDCIM() {
249         if (Build.VERSION.SDK_INT >= 19) {
250             //兼容android4.4版本,只扫描存放照片的目录
251             MediaScannerConnection.scanFile(Latte.getApplicationContext(),
252                     new String[]{Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath()},
253                     null, null);
254         } else {
255             //扫描整个SD卡来更新系统图库,当文件很多时用户体验不佳,且不适合4.4以上版本
256             Latte.getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" +
257                     Environment.getExternalStorageDirectory())));
258         }
259     }
260 
261     /**
262      * 读取raw目录中的文件,并返回为字符串
263      */
264     public static String getRawFile(int id) {
265         final InputStream is = Latte.getApplicationContext().getResources().openRawResource(id);
266         final BufferedInputStream bis = new BufferedInputStream(is);
267         final InputStreamReader isr = new InputStreamReader(bis);
268         final BufferedReader br = new BufferedReader(isr);
269         final StringBuilder stringBuilder = new StringBuilder();
270         String str;
271         try {
272             while ((str = br.readLine()) != null) {
273                 stringBuilder.append(str);
274             }
275         } catch (IOException e) {
276             e.printStackTrace();
277         } finally {
278             try {
279                 br.close();
280                 isr.close();
281                 bis.close();
282                 is.close();
283             } catch (IOException e) {
284                 e.printStackTrace();
285             }
286         }
287         return stringBuilder.toString();
288     }
289 
290 
291     public static void setIconFont(String path, TextView textView) {
292         final Typeface typeface = Typeface.createFromAsset(Latte.getApplicationContext().getAssets(), path);
293         textView.setTypeface(typeface);
294     }
295 
296     /**
297      * 读取assets目录下的文件,并返回字符串
298      */
299     public static String getAssetsFile(String name) {
300         InputStream is = null;
301         BufferedInputStream bis = null;
302         InputStreamReader isr = null;
303         BufferedReader br = null;
304         StringBuilder stringBuilder = null;
305         final AssetManager assetManager = Latte.getApplicationContext().getAssets();
306         try {
307             is = assetManager.open(name);
308             bis = new BufferedInputStream(is);
309             isr = new InputStreamReader(bis);
310             br = new BufferedReader(isr);
311             stringBuilder = new StringBuilder();
312             String str;
313             while ((str = br.readLine()) != null) {
314                 stringBuilder.append(str);
315             }
316         } catch (IOException e) {
317             e.printStackTrace();
318         } finally {
319             try {
320                 if (br != null) {
321                     br.close();
322                 }
323                 if (isr != null) {
324                     isr.close();
325                 }
326                 if (bis != null) {
327                     bis.close();
328                 }
329                 if (is != null) {
330                     is.close();
331                 }
332                 assetManager.close();
333             } catch (IOException e) {
334                 e.printStackTrace();
335             }
336         }
337         if (stringBuilder != null) {
338             return stringBuilder.toString();
339         } else {
340             return null;
341         }
342     }
343 
344     public static String getRealFilePath(final Context context, final Uri uri) {
345         if (null == uri) return null;
346         final String scheme = uri.getScheme();
347         String data = null;
348         if (scheme == null)
349             data = uri.getPath();
350         else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
351             data = uri.getPath();
352         } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
353             final Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
354             if (null != cursor) {
355                 if (cursor.moveToFirst()) {
356                     final int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
357                     if (index > -1) {
358                         data = cursor.getString(index);
359                     }
360                 }
361                 cursor.close();
362             }
363         }
364         return data;
365     }
366 }

 【保存文件类的封装】

 云炬Android开发笔记 5-8文件下载功能设计与实现

云炬Android开发笔记 5-8文件下载功能设计与实现

【继续封装com.flj.latte.net.download.DownloadHandler】

云炬Android开发笔记 5-8文件下载功能设计与实现

云炬Android开发笔记 5-8文件下载功能设计与实现

【调用的方法】在后面的使用文件下载然后更新应用程序;

云炬Android开发笔记 5-8文件下载功能设计与实现

云炬Android开发笔记 5-8文件下载功能设计与实现

【提交代码】

 云炬Android开发笔记 5-8文件下载功能设计与实现