android 下載工具類,賊好用


使用方法:只需要傳入一個下載的文件路徑+文件名,然后再傳入一個要下載的文件的url

該下載工具類需要和 okhttp網絡請求庫一起使用,如果你項目內沒有,需要引入此庫才能使用

implementation("com.squareup.okhttp3:okhttp:3.14.1")

  

DownloadUtil.get().download(url, getDiskCacheDir(mContext).toString(), "file."+hzname, new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(File file) {//下載成功
                Log.e("file path",""+file.toString());
                readerView.post(new Runnable() {
                    @Override
                    public void run() {
                        //存儲一份 待網絡不可用時打開此鏈接
                        Storage.saveFilePath(file.toString());
                        openFile(file.toString());
                    }
                });

            }

            @Override
            public void onDownloading(int progress) {//下載進度
                Log.e("progress:===",progress+"");
            }

            @Override
            public void onDownloadFailed(Exception e) {//下載異常
                if (!Storage.getFilePath().equals("")) {
                    openFile(Storage.getFilePath());
                }
            }
        });

  獲取app包名目錄下的下載路徑

 public String getDiskCacheDir(Context context) {
        String cachePath = null;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }

  //具體的下載工具類

/**
 * Created by alert on 2020/08/21.
 */

public class DownloadUtil {
    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 url          下載連接
     * @param destFileDir  下載的文件儲存目錄
     * @param destFileName 下載文件名稱
     * @param listener     下載監聽
     */
    public void download(final String url, final String destFileDir, final String destFileName, 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(e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 儲存下載文件的目錄
                File dir = new File(destFileDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir, destFileName);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    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(e);
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    public interface OnDownloadListener {
        /**
         * @param file 下載成功后的文件
         */
        void onDownloadSuccess(File file);

        /**
         * @param progress 下載進度
         */
        void onDownloading(int progress);

        /**
         * @param e 下載異常信息
         */
        void onDownloadFailed(Exception e);
    }

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM