当前位置: 首页 > backend >正文

Android 文件下载

前言

总体思路:下载文件到应用缓存路径,在相册创建文件夹,Copy过去,通知相册刷新。

下载文件到APP缓存路径,这样可避免Android高版本读取本地权限问题,

准备

implementation 'com.squareup.okhttp3:okhttp:3.6.0'
implementation 'com.squareup.okio:okio:1.11.0'

调用

url:文件url

path:储存的路径

应用缓存路径:getExternalCacheDir().getPath()

DownloadUtil.get().download(url, path, new DownloadUtil.OnDownloadListener() {@Overridepublic void onDownloadSuccess(File file) {//下载成功    handler.sendEmptyMessage(1);}@Overridepublic void onDownloading(int progress) {//进度条handler.sendEmptyMessage(progress);}@Overridepublic void onDownloadFailed() {//下载失败handler.sendEmptyMessage(-1);}});

复制到相册目录

DownloadUtil.createFiles(downLoadFile);

通知相册刷新

DownloadUtil.updateDCIM(this,downloadFile);

工具类

/*** 下载工具类* martin* 2021.7.21*/
public class DownloadUtil {private static final String TAG = DownloadUtil.class.getName();private static DownloadUtil downloadUtil;private final OkHttpClient okHttpClient;public static DownloadUtil get() {if (downloadUtil == null) {downloadUtil = new DownloadUtil();}return downloadUtil;}private DownloadUtil() {okHttpClient = new OkHttpClient();}/*** 复制单个文件** @param oldPath$Name String 原文件路径+文件名 如:data/user/0/com.test/files/abc.txt* @param newPath$Name String 复制后路径+文件名 如:data/user/0/com.test/cache/abc.txt* @return <code>true</code> if and only if the file was copied;* <code>false</code> otherwise*/public static boolean copyFile(String oldPath$Name, String newPath$Name) {try {File oldFile = new File(oldPath$Name);if (!oldFile.exists()) {Log.e("--Method--", "copyFile:  oldFile not exist.");return false;} else if (!oldFile.isFile()) {Log.e("--Method--", "copyFile:  oldFile not file.");return false;} else if (!oldFile.canRead()) {Log.e("--Method--", "copyFile:  oldFile cannot read.");return false;}/* 如果不需要打log,可以使用下面的语句if (!oldFile.exists() || !oldFile.isFile() || !oldFile.canRead()) {return false;}*/FileInputStream fileInputStream = new FileInputStream(oldPath$Name);FileOutputStream fileOutputStream = new FileOutputStream(newPath$Name);byte[] buffer = new byte[1024];int byteRead;while (-1 != (byteRead = fileInputStream.read(buffer))) {fileOutputStream.write(buffer, 0, byteRead);}fileInputStream.close();fileOutputStream.flush();fileOutputStream.close();return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 通知相册更新** @param context* @param newFile*/public void updateDCIM(Context context, File newFile) {File cameraPath = new File(dcimPath, "Camera");File imgFile = new File(cameraPath, newFile.getAbsolutePath());if (imgFile.exists()) {Uri uri = Uri.fromFile(imgFile);Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);intent.setData(uri);context.sendBroadcast(intent);}}/*** url 下载连接* saveDir 储存下载文件的SDCard目录* listener 下载监听*/public void download(final String url, final String saveDir,final OnDownloadListener listener) {Request request = new Request.Builder().url(url).build();okHttpClient.newCall(request).enqueue(new Callback() {@Overridepublic void onFailure(Call call, IOException e) {// 下载失败listener.onDownloadFailed();}@Overridepublic void onResponse(Call call, Response response) throws IOException {InputStream is = null;byte[] buf = new byte[2048];int len = 0;FileOutputStream fos = null;// 储存下载文件的目录String savePath = isExistDir(saveDir);try {is = response.body().byteStream();long total = response.body().contentLength();File file = new File(savePath, getNameFromUrl(url));fos = new FileOutputStream(file);long sum = 0;while ((len = is.read(buf)) != -1) {fos.write(buf, 0, len);sum += len;int progress = (int) (sum * 1.0f / total * 100);// 下载中listener.onDownloading(progress);}fos.flush();// 下载完成listener.onDownloadSuccess(file);} catch (Exception e) {listener.onDownloadFailed();} finally {try {if (is != null)is.close();} catch (IOException e) {}try {if (fos != null)fos.close();} catch (IOException e) {}}}});}/*** saveDir* 判断下载目录是否存在*/private static String isExistDir(String saveDir) throws IOException {// 下载位置File downloadFile = new File(saveDir);if (!downloadFile.mkdirs()) {downloadFile.createNewFile();}String savePath = downloadFile.getAbsolutePath();return savePath;}//系统相册路径static String dcimPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();/*** 创建文件夹*/public static void createFiles(File oldFile) {try {File file = new File(isExistDir(dcimPath + "/xxx"));String newPath = file.getPath() + "/" + oldFile.getName();Log.d("TAG", "createFiles111: " + oldFile.getPath() + "--" + newPath);if (copyFile(oldFile.getPath(), newPath)) {Log.d("TAG", "createFiles222: " + oldFile.getPath() + "--" + newPath);}} catch (IOException e) {e.printStackTrace();}}/*** url* 从下载连接中解析出文件名*/@NonNullpublic static String getNameFromUrl(String url) {return url.substring(url.lastIndexOf("/") + 1);}public interface OnDownloadListener {/*** 下载成功*/void onDownloadSuccess(File file);/*** @param progress 下载进度*/void onDownloading(int progress);/*** 下载失败*/void onDownloadFailed();}
}

http://www.xdnf.cn/news/11298.html

相关文章:

  • 基于MapGuide的在线WebGIS站点介绍
  • route add命令详解
  • 【经典收藏】深度技术ghost官方原版XP系统sp3下载地址 ...
  • 常用网页广告代码全集-js广告代码大全-个人收藏
  • Java语言 static (静态变量、实例变量、局部变量、静态方法)
  • 数据结构课程设计
  • WinPE安装与卸载(微PE版)
  • Matlab中plot画图线型、标记和颜色
  • 黑客完全修炼手册(收藏)
  • Python学习之海龟绘图
  • 计算机丢失UxTheme无法修复,win10系统丢失uxtheme.dll的修复办法
  • 托管代码
  • slot插槽以及具名插槽
  • nagios 安装
  • 使用深度学习检测混凝土结构中的表面裂缝
  • mapinfo10.5破解版安装
  • CSS滤镜(Filter)全攻略
  • ROS官方教程[翻译]---message_filter的使用
  • VC++类型转换整理(转载)
  • Edius简易教程
  • 编译原理课程设计(编写编译器)
  • 嵌入式外设集 -- 液晶显示模块(LCD1602)
  • DTFD-MIL: Double-Tier Feature Distillation Multiple Instance Learning for WSI_论文笔记
  • 开源建站系统——phpnuke8安装步骤
  • 把Flash动画轻松转成GIF图片
  • 使用客户端脚本
  • 旁注原理
  • 【星界探索——通信卫星】铱星:从“星光坠落”到“涅槃重生”,万字长文分析铱星卫星系统市场
  • 盗号工具手机版下载/手机版盗号工具下载网站-详细信息安全教学
  • 史上最全免费收录网站搜索引擎登录口(经典)