Android Implementation File Download

  • 2021-12-13 09:49:57
  • OfStack

Preface

General idea: Download the file to the application cache path, create the folder in the album, Copy past, notify the album refresh.

Download the file to the APP cache path to avoid the Android high version read local permission problem,

Prepare


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

Call

url: File url

path: Saved path

Application cache path: getExternalCacheDir (). getPath ()


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

Copy to Album Catalog


DownloadUtil.createFiles(downLoadFile);

Notify album refresh


DownloadUtil.updateDCIM(this,downloadFile);

Tool class


/**
 *  Download tool class 
 * 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();
    }
 
    /**
     *  Copy a single file 
     *
     * @param oldPath$Name String  Original file path + Filename   Such as: data/user/0/com.test/files/abc.txt
     * @param newPath$Name String  Post-copied path + Filename   Such as: 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;
            }
 
            /*  If you don't need to call log You can use the following statement 
            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;
        }
    }
 
    /**
     *  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, 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  Download connection 
     * saveDir  That stores the downloaded file SDCard Directory 
     * listener  Download monitor 
     */
    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) {
                //  Download failed 
                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;
                //  Directory to store downloaded files 
                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);
                        //  Downloading 
                        listener.onDownloading(progress);
                    }
                    fos.flush();
                    //  Download complete 
                    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
     *  Determining whether the download directory exists 
     */
    private static String isExistDir(String saveDir) throws IOException {
        //  Download location 
        File downloadFile = new File(saveDir);
        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile();
        }
        String savePath = downloadFile.getAbsolutePath();
        return savePath;
    }
 
    // System album path 
    static String dcimPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
 
    /**
     *  Create a folder 
     */
    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
     *  Parse the file name from the download connection 
     */
    @NonNull
    public static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }
 
    public interface OnDownloadListener {
        /**
         *  Download succeeded 
         */
        void onDownloadSuccess(File file);
 
        /**
         * @param progress  Download progress 
         */
        void onDownloading(int progress);
 
        /**
         *  Download failed 
         */
        void onDownloadFailed();
    }

}

Related articles: