SoFunction
Updated on 2025-04-07

Android implementation file download

Preface

Overall idea: Download the file to the application cache path, create a folder in the album, copy it over, and notify the album to refresh.

Download the file to the APP cache path, which can avoid the problem of reading local permissions in higher versions of Android.

Prepare

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

Call

url: file url

path: the stored path

Application cache path: getExternalCacheDir().getPath()

().download(url, path, new () {
            @Override
            public void onDownloadSuccess(File file) {
                //Download successfully                (1);
            }
 
            @Override
            public void onDownloading(int progress) {
                //Progress bar                (progress);
            }
 
            @Override
            public void onDownloadFailed() {
                //Download failed                (-1);
            }
        });

Copy to album directory

(downLoadFile);

Notify album refresh

(this,downloadFile);

Tools

/**
  * Download tool class
  * martin
  * 2021.7.21
  */
public class DownloadUtil {
    private static final String TAG = ();
    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();
    }
 
    /**
      * Copy a single file
      *
      * @param oldPath$Name String Original file path + file name For example: data/user/0//files/
      * @param newPath$Name String Path+file name after copying, such as: data/user/0//cache/
      * @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 (!()) {
                ("--Method--", "copyFile:  oldFile not exist.");
                return false;
            } else if (!()) {
                ("--Method--", "copyFile:  oldFile not file.");
                return false;
            } else if (!()) {
                ("--Method--", "copyFile:  oldFile cannot read.");
                return false;
            }
 
            /* If you do not need to log, you can use the following statement
             if (!() || !() || !()) {
                 return false;
             }
             */
 
            FileInputStream fileInputStream = new FileInputStream(oldPath$Name);
            FileOutputStream fileOutputStream = new FileOutputStream(newPath$Name);
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = (buffer))) {
                (buffer, 0, byteRead);
            }
            ();
            ();
            ();
            return true;
        } catch (Exception e) {
            ();
            return false;
        }
    }
 
    /**
      * Notify album updates
      *
      * @param context
      * @param newFile
      */
    public void updateDCIM(Context context, File newFile) {
        File cameraPath = new File(dcimPath, "Camera");
        File imgFile = new File(cameraPath, ());
        if (()) {
            Uri uri = (imgFile);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            (uri);
            (intent);
        }
    }
 
 
    /**
      * url download connection
      * saveDir SDCard directory that stores downloaded files
      * listener download monitor
      */
    public void download(final String url, final String saveDir,
                         final OnDownloadListener listener) {
        Request request = new ().url(url).build();
        (request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // Download failed                ();
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // directory to store downloaded files                String savePath = isExistDir(saveDir);
                try {
                    is = ().byteStream();
                    long total = ().contentLength();
                    File file = new File(savePath, getNameFromUrl(url));
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = (buf)) != -1) {
                        (buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // Downloading                        (progress);
                    }
                    ();
                    // Download completed                    (file);
                } catch (Exception e) {
                    ();
                } finally {
                    try {
                        if (is != null)
                            ();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            ();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }
 
    /**
      * saveDir
      * Determine whether the download directory exists
      */
    private static String isExistDir(String saveDir) throws IOException {
        // Download location        File downloadFile = new File(saveDir);
        if (!()) {
            ();
        }
        String savePath = ();
        return savePath;
    }
 
    //System album path    static String dcimPath = (Environment.DIRECTORY_DCIM).getAbsolutePath();
 
    /**
      * Create folder
      */
    public static void createFiles(File oldFile) {
        try {
            File file = new File(isExistDir(dcimPath + "/xxx"));
            String newPath = () + "/" + ();
            ("TAG", "createFiles111: " + () + "--" + newPath);
            if (copyFile((), newPath)) {
                ("TAG", "createFiles222: " + () + "--" + newPath);
            }
        } catch (IOException e) {
            ();
        }
    }
 
 
    /**
      * url
      * Parses file name from download connection
      */
    @NonNull
    public static String getNameFromUrl(String url) {
        return (("/") + 1);
    }
 
    public interface OnDownloadListener {
        /**
          * Download successfully
          */
        void onDownloadSuccess(File file);
 
        /**
          * @param progress Download progress
          */
        void onDownloading(int progress);
 
        /**
          * Download failed
          */
        void onDownloadFailed();
    }

}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.