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() {
            @Override
            public void onDownloadSuccess(File file) {
                //下载成功
                handler.sendEmptyMessage(1);
            }

            @Override
            public void onDownloading(int progress) {
                //进度条
                handler.sendEmptyMessage(progress);
            }

            @Override
            public 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() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                listener.onDownloadFailed();
            }

            @Override
            public 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
     * 从下载连接中解析出文件名
     */
    @NonNull
    public 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();
    }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Android 将文件下载到指定目录的实现代码

    废话不多说了额,直接给大家贴代码了,具体代码如下所示: /** * 下载指定路径的文件,并写入到指定的位置 * * @param dirName * @param fileName * @param urlStr * @return 返回0表示下载成功,返回1表示下载出错 */ public int downloadFile(String dirName, String fileName, String urlStr) { OutputStream output = null; try { //

  • Android文件下载功能实现代码

    本文实例为大家分享了Android文件下载功能的具体代码,供大家参考,具体内容如下 1.普通单线程下载文件: 直接使用URLConnection.openStream()打开网络输入流,然后将流写入到文件中! public static void downLoad(String path,Context context)throws Exception { URL url = new URL(path); InputStream is = url.openStream(); //截取最后的文件名

  • Android实现简单的文件下载与上传

    文件下载 /** * 下载服务 IntentService * 生命周期: * 1>当第一次启动IntentService时,Android容器 * 将会创建IntentService对象. * 2>IntentService将会在工作线程中轮循消息队列, * 执行每个消息对象中的业务逻辑. * 3>如果消息队列中依然有消息,则继续执行, * 如果消息队列中的消息已经执行完毕, * IntentService将会自动销毁,执行onDestroy方法. */ public class Do

  • android实现文件下载功能

    android 在网络上下载文件,供大家参考,具体内容如下 步骤 : 1.使用HTTP协议下载文件 - 创建一个HttpURLConnection对象 : HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); - 获取一个InputStream对象 : urlConn.getInputStream() - 访问网络的权限 : android.permission.INTERNET 2.将下载的文件写入SDCAR

  • Android 文件下载三种基本方式

    一.自己封装URLConnection 连接请求类 public void downloadFile1() { try{ //下载路径,如果路径无效了,可换成你的下载路径 String url = "http://c.qijingonline.com/test.mkv"; String path = Environment.getExternalStorageDirectory().getAbsolutePath(); final long startTime = System.cur

  • Android基于HttpUrlConnection类的文件下载实例代码

    废话不多说了,直接给大家贴代码了,具体代码如所示: /** * get方法的文件下载 * <p> * 特别说明 android中的progressBar是google唯一的做了处理的可以在子线程中更新UI的控件 * * @param path */ private void httpDown(final String path) { new Thread() { @Override public void run() { URL url; HttpURLConnection connectio

  • Android文件下载进度条的实现代码

    main.xml: 复制代码 代码如下: <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_paren

  • Android Retrofit文件下载进度显示问题的解决方法

    综述 在Retrofit2.0使用详解这篇文章中详细介绍了retrofit的用法.并且在retrofit中我们可以通过ResponseBody进行对文件的下载.但是在retrofit中并没有为我们提供显示下载进度的接口.在项目中,若是用户下载一个文件,无法实时给用户显示下载进度,这样用户的体验也是非常差的.那么下面就介绍一下在retrofit用于文件的下载如何实时跟踪下载进度. 演示 Retrofit文件下载进度更新的实现 在retrofit2.0中他依赖于Okhttp,所以如果我们需要解决这个

  • Android实现文件下载进度显示功能

    和大家一起分享一下学习经验,如何实现Android文件下载进度显示功能,希望对广大初学者有帮助. 先上效果图: 上方的蓝色进度条,会根据文件下载量的百分比进行加载,中部的文本控件用来现在文件下载的百分比,最下方的ImageView用来展示下载好的文件,项目的目的就是动态向用户展示文件的下载量. 下面看代码实现:首先是布局文件: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xm

  • Android zip文件下载和解压实例

    下载:DownLoaderTask.java 复制代码 代码如下: package com.johnny.testzipanddownload; import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IO

随机推荐