广告
返回顶部
首页 > 资讯 > 移动开发 >Android实现文件下载
  • 592
分享到

Android实现文件下载

2024-04-02 19:04:59 592人浏览 薄情痞子
摘要

前言 总体思路:下载文件到应用缓存路径,在相册创建文件夹,Copy过去,通知相册刷新。 下载文件到APP缓存路径,这样可避免Android高版本读取本地权限问题, 准备 impl

前言

总体思路:下载文件到应用缓存路径,在相册创建文件夹,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);

工具



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();
    }
 
    
    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;
            }
 
            
 
            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;
        }
    }
 
    
    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);
        }
    }
 
 
    
    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) {
                    }
                }
            }
        });
    }
 
    
    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();
        }
    }
 
 
    
    @NonNull
    public static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }
 
    public interface OnDownloadListener {
        
        void onDownloadSuccess(File file);
 
        
        void onDownloading(int progress);
 
        
        void onDownloadFailed();
    }

}

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

--结束END--

本文标题: Android实现文件下载

本文链接: https://www.lsjlt.com/news/131101.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作