天天看點

Android okHttp檔案下載下傳并帶進度條的demo(簡單工具類)

根據okHttp簡單的封裝了一個根據url下載下傳檔案并更新進度的工具類,在此記錄下,以後要使用可以進行參考

先來看看效果圖:

Android okHttp檔案下載下傳并帶進度條的demo(簡單工具類)

接下來看看具體的代碼實作

首先在:app中添加項目對于Okhttp的依賴:

//okhttp
compile 'com.squareup.okhttp3:okhttp:3.3.1'
           

建立Java檔案DownloadUtil.java

package com.demo.test;

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 on 2017/10/16.
 */

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

使用方法

/**
     * 檔案下載下傳
     *
     * @param url
     */
    public void downFile(String url) {
        progressDialog = new ProgressDialog(SplashActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("正在下載下傳");
        progressDialog.setMessage("請稍後...");
        progressDialog.setProgress(0);
        progressDialog.setMax(100);
        progressDialog.show();
        progressDialog.setCancelable(false);
        DownloadUtil.get().download(url, Environment.getExternalStorageDirectory().getAbsolutePath(), "kuoke.apk", new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(File file) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                //下載下傳完成進行相關邏輯操作
                
            }

            @Override
            public void onDownloading(int progress) {
                progressDialog.setProgress(progress);
            }

            @Override
            public void onDownloadFailed(Exception e) {
                //下載下傳異常進行相關提示操作
            }
        });
    }
           

簡單的工具封裝,僅供參考,大神多多指教,一起進步

繼續閱讀