下载文件或视频,下载完成后自动打开

Posted mo_weifeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了下载文件或视频,下载完成后自动打开相关的知识,希望对你有一定的参考价值。

遵循以下流程

1、加权限

    <!-- 在sdcard中创建/删除文件的权限 -->
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

2、添加FileProvider(打开文件用)

      <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="$applicationId.fileProvider2"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>

filepaths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <paths>
        <external-path path="." name="jiuxing" />
    </paths>
</paths>

3、先创建文件夹,下载用

视频放在Picture,文件放在Download

public static String getSystemVideoFolder(Context context, String folderName) 
        String folder = getSystemVideoDir(context)
                + File.separator + folderName;

        LogUtils.i("folder=" + folder);

        File folderFile = new File(folder);

        if (!folderFile.exists()) 
            boolean isSuccess = folderFile.mkdirs();
            LogUtils.i("创建文件夹路径是否成功=" + isSuccess);
        
        return folder;
    

    public static String getSystemVideoDir(Context context) 
        File folder = Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES);
        return folder.getAbsolutePath();
    

    public static String getSystemFileFolder(Context context, String folderName) 
        String folder = getSystemFileDir(context)
                + File.separator + folderName;

        LogUtils.i("folder=" + folder);

        File folderFile = new File(folder);

        if (!folderFile.exists()) 
            boolean isSuccess = folderFile.mkdirs();
            LogUtils.i("创建文件夹路径是否成功=" + isSuccess);
        
        return folder;
    
        public static String getSystemFileDir(Context context) 
        File folder = Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS);
        return folder.getAbsolutePath();
    

现在就可以得到下载的目录了

        String dir = FolderUtil.getSystemVideoFolder(getContext(), "jiuxing");
       String dir = FolderUtil.getSystemFileFolder(getContext(), "jiuxing");

4、下载类

DownloadManager

package com.zues.module_network.util;

import android.text.TextUtils;
import android.util.Log;


import androidx.annotation.NonNull;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by heavyrainlee on 20/02/2018.
 */

public class DownloadManager 

    private final String TAG = getClass().getSimpleName();
    private static DownloadManager downloadManager;
    private final OkHttpClient okHttpClient;

    public static DownloadManager get() 
        if (downloadManager == null) 
            downloadManager = new DownloadManager();
        
        return downloadManager;
    

    private DownloadManager() 
        okHttpClient = new OkHttpClient();
    

    public void download(final String url, final String saveDir, final OnDownloadListener listener) 
        download(url, saveDir, listener);
    

    public void download(final String url, final String saveDir, String name, 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.onFail();
            

            @Override
            public void onResponse(Call call, Response response) throws IOException 
                InputStream is = null;
                FileOutputStream fos = null;
                try 
                    byte[] buf = new byte[2048];
                    int len = 0;
                    // 储存下载文件的目录
                    String savePath = isExistDir(saveDir);

                    String fileName = TextUtils.isEmpty(name) ? getNameFromUrl(url) : name;
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(savePath, fileName);
                    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.onProgress(progress);
                    
                    fos.flush();
                    // 下载完成
                    listener.onSuccess(file);
                 catch (Exception e) 
                    Log.i(TAG, "onResponse: ");
                    listener.onFail();

                 finally 
                    try 
                        if (is != null) 
                            is.close();
                        
                     catch (IOException e) 
                    
                    try 
                        if (fos != null) 
                            fos.close();
                        
                     catch (IOException e) 
                    
                
            
        );
    

    /**
     * @param saveDir
     * @return
     * @throws IOException 判断下载目录是否存在
     */
    private String isExistDir(String saveDir) throws IOException 
        // 下载位置
        File downloadFile = new File(saveDir);
        if (!downloadFile.mkdirs()) 
            downloadFile.createNewFile();
        
        return downloadFile.getAbsolutePath();
    

    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    @NonNull
    private String getNameFromUrl(String url) 
        return url.substring(url.lastIndexOf("/") + 1);
    

    public interface OnDownloadListener 
        /**
         * 下载成功
         */
        void onSuccess(File file);

        /**
         * @param progress 下载进度
         */
        void onProgress(int progress);

        /**
         * 下载失败
         */
        void onFail();
    

5、下载完直接打开文件,通知图库更新

private void downloadVideo(String url, String name) 
        String dir = FolderUtil.getSystemVideoFolder(getContext(), "jiuxing");

        CustomDialogUtils.showPosDialog2(getContext(), null, "请下载后观看", "取消", "立即下载", new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                showDialog("正在下载");
                DownloadManager.get().download(url, dir, name, new DownloadManager.OnDownloadListener() 
                    @Override
                    public void onSuccess(File file) 

                        dismissDialog();
//                        showToast("视频已下载:" + dir + "/" + name);

                        // 通知图库更新
                        getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                                Uri.fromFile(new File(file.getPath()))));

                        //传递的数据
                        Bundle bundle = new Bundle();
                        bundle.putString("file", file.getAbsolutePath());
                        //发送数据
                        Message message = Message.obtain();
                        message.setData(bundle);   //message.obj=bundle  传值也行
                        mVideoHandler.sendMessage(message);

//                        打开文件
//                        FileOpenUtil.openFile(getContext(), file);

                        LogUtils.e("文件已下载:" + dir + "/" + name);
                    

                    @Override
                    public void onProgress(int progress) 
                        LogUtils.e("progress=" + progress);
                    

                    @Override
                    public void onFail() 
                        dismissDialog();
                        showToast("视频下载失败,请刷新后重试");
                    
                );
            
        , null);

    
 private void downloadFile(String url, String name) 
        String dir = FolderUtil.getSystemFileFolder(getContext(), "jiuxing");

        CustomDialogUtils.showPosDialog2(getContext(), null, "请下载后查看", "取消", "立即下载", new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                showDialog("正在下载");
                DownloadManager.get().download(url, dir, name, new DownloadManager.OnDownloadListener() 
                    @Override
                    public void onSuccess(File file) 

                        dismissDialog();
//                        showToast("文件已下载:" + dir + "/" + name);

                       //传递的数据
                        Bundle bundle = new Bundle();
                        bundle.putString("file", file.getAbsolutePath());
                        //发送数据
                        Message message = Message.obtain();
                        message.setData(bundle);   //message.obj=bundle  传值也行
                        mFileHandler.sendMessage(message);

                        //打开文件
//                        FileOpenUtil.openFile(getContext(), file);


                        LogUtils.e("文件已下载:" + dir + "/" + name);
                    

                    @Override
                    public void onProgress(int progress) 
                        LogUtils.e("progress=" + progress);
                    

                    @Override
                    public void onFail() 
                        dismissDialog();
                        showToast("文件下载失败,请刷新后重试");
                    
                );
            
        , null);

    
Handler mVideoHandler = new Handler()
        @Override
        public void handleMessage(Message msg) 
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            String url = bundle.getString("file");

            //打开文件
            FileOpenUtil.openFile(getContext(), new File(url));
        
    ;
    Handler mFileHandler = new Handler()
        @Override
        public void handleMessage(Message msg) 
            super.handleMessage(msg);

            Bundle bundle = msg.getData();
            String url = bundle.getString("file");

            //打开文件
            FileOpenUtil.openFile(getContext(), new File(url));
        
    ;

6、打开文件工具

FileOpenUtil

package com.zues.module_base.base_util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.webkit.MimeTypeMap;
import android.widget.视频文件中嵌入URL地址是怎么回事?可以去掉吗?

mp4格式视频怎么下载?

为啥下载的PDF文件打不开?要下载啥软件?

下载完成后如何显示app选择器

用手机的浏览器下载压缩文件时,文件名是乱码,而且下载了之后打不开,这是怎么回事

监控页面打不开