retrofit2+okhttp3下載文件

     沒有加Rxjava支持,需要的自行加上即可
    ...別忘了請求權限

代碼

    Retrofit.Builder builder = new Retrofit.Builder()
            .baseUrl(Utils.getBaseUrl());

    //下載進度的監(jiān)聽器
    OkHttpClient client = new OkHttpClient.Builder()
            .addNetworkInterceptor(new Interceptor() {

                @Override
                public Response intercept(Chain chain) throws IOException {

                    Response orginalResponse = chain.proceed(chain.request());
                    return orginalResponse.newBuilder()
                            .body(new ProgressResponseBody(orginalResponse.body(), new ProgressListener() {
                                @Override
                                public void onProgress(long progress, long total, boolean done) {

                                    // 計算已下載文件大小的百分比
                                    BigDecimal totalSize = new BigDecimal(((total / 1024f) / 1024f)).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    BigDecimal progressSize = new BigDecimal(((progress / 1024f) / 1024f)).setScale(2, BigDecimal.ROUND_HALF_UP);

                                    if (TextUtils.equals(String.valueOf(totalSize), "0.00")) {
                                        SmartToast.show("目標文件為空文件");
                                        return;
                                    }

                                    Log.d(TAG, "onProgress: 共" + totalSize + "MB,已下載" + progressSize + "MB");

                                    if ((int) ((progress * 100) / total) > newProgress) {
                                        newProgress = (int) ((progress * 100) / total);

                                        Message msg = mHandler.obtainMessage();
                                        msg.what = 100;
                                        msg.obj = newProgress;
                                        mHandler.sendMessage(msg);
                                        Log.d(TAG, "onProgress: 下載百分比-->" + newProgress);
                                    }
                                }
                            }))
                            .build();
                }
            })
            .build();


    //加載監(jiān)聽器
    SystemApis download = builder.client(client).build().create(SystemApis.class);
    //開始下載
    download.downloadApk().enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
            //下載完成,此時下載的內容還在body里面,吊桶該方法將body存到SD卡上,返回true則保存成功
            try {
                if (Utils.writeFileToDisk(response.body()))
                    mHandler.sendEmptyMessage(101);
            } catch (Exception e) {
                Log.e(TAG, "onResponse: ", e);
                updateDialog.dismiss();
                SmartToast.show("下載異常,可能服務器并未有該文件存在");
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            // 甩鍋大法好
            SmartToast.show("更新失敗,網絡異常");
        }
    });

這個是Handler

            case 100://正在下載
                int progress = (int) msg.obj;
                updateDialog.setProgress(progress);
                break;

            case 101://下載完成
                updateDialog.dismiss();
                SmartToast.show("下載完成,準備安裝");
                Utils.installPackage(LoginActivity.this, Constant.SDCardPath.APKName);
                break;
            case 102://保存失?。ɑ蛘呦螺d失?。?                updateDialog.dismiss();
                SmartToast.show("遇到未知錯誤,請重新下載");
                break;

ProcessResponseBody

    import okhttp3.MediaType;
    import okhttp3.ResponseBody;
    import okio.Buffer;
    import okio.BufferedSource;
    import okio.ForwardingSource;
    import okio.Okio;
    import okio.Source;

    /**
    * 重寫ResponseBody,實現(xiàn)監(jiān)聽下載進度功能
    * Created by danie on 2017/11/22.
    */
   public class ProgressResponseBody extends ResponseBody {

   private final ResponseBody responseBody;
   private final ProgressListener listener;
   private BufferedSource bufferedSource;

    public ProgressResponseBody(ResponseBody responseBody, ProgressListener listener) {
        this.responseBody = responseBody;
        this.listener = listener;
    }

    @Nullable
    @Override
        public MediaType contentType() {
        return responseBody.contentType();
     }

     @Override
      public long contentLength() {
          return responseBody.contentLength();
      }

    @Override
    public BufferedSource source() {
        if (null == bufferedSource) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    private Source source(Source source) {
        return new ForwardingSource(source) {
            long totalBytesRead = 0L;

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                l ong bytesRead = super.read(sink, byteCount);
                totalBytesRead += bytesRead != -1 ? bytesRead : 0;
                listener.onProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
                return bytesRead;
            }
        };
    }
}

ProgressListener

    /**
     * Retrofit下載文件時下載進度的回調
     * Created by danie on 2017/11/22.
     */
    public interface ProgressListener {
        /**
         * @param progress     已經下載或上傳字節(jié)數(shù)
         * @param total        總字節(jié)數(shù)
         * @param done         是否完成
         */
        void onProgress(long progress, long total, boolean done);
     }

OJBK,現(xiàn)在才是真的要下班了!

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容