Android下載網路pdf檔案儲存至本地

思敏吖發表於2020-10-26

/**
 * 檔案下載工具類(單例模式)
 */

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);
    }
}


   @Override
                        public void onmenuclick(int id, String name, String url) {
                            if (TextUtils.isEmpty(url)) {
                                ToastUtil.show("未發現下載文件");
                                return;
                            } else {
                                downFile(name, url);
                            }
                        }
                    });
  /**
     * 下載檔案
     *
     * @param name
     * @param urlString
     */
    public void downFile(String name, String urlString) {
        DownloadUtil.get().download(urlString, Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Download", name + ".pdf", new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(File file) {
                Log.v(TAG, "下載成功,檔案已存入手機內部儲存裝置根目錄下Download資料夾中");
                Looper.prepare();//增加部分
                Looper.loop();//增加部分
            }

            @Override
            public void onDownloading(int progress) {
                Log.v(TAG, "下載進度" + progress);
//                progressDialog.setProgress(progress);
            }

            @Override
            public void onDownloadFailed(Exception e) {
//                if (progressDialog != null && progressDialog.isShowing()) {
//                    progressDialog.dismiss();
//                }

            }
        });
    }

相關文章