Square`s OkHttp. Download progress

前端 未结 3 1257
我寻月下人不归
我寻月下人不归 2021-01-31 00:01

Is there any way to get downloading file progress when using square`s OkHttp?

I did not find any solution in Recipes.

They have class Call which can get content

相关标签:
3条回答
  • 2021-01-31 00:25

    Oops answer was obvious. Sorry for dumb question. Just need to read InputStream as usual.

    private class AsyncDownloader extends AsyncTask<Void, Long, Boolean> {
        private final String URL = "file_url";
    
        @Override
        protected Boolean doInBackground(Void... params) {
            OkHttpClient httpClient = new OkHttpClient();
            Call call = httpClient.newCall(new Request.Builder().url(URL).get().build());
            try {
                Response response = call.execute();
                if (response.code() == 200) {
                    InputStream inputStream = null;
                    try {
                        inputStream = response.body().byteStream();
                        byte[] buff = new byte[1024 * 4];
                        long downloaded = 0;
                        long target = response.body().contentLength();
    
                        publishProgress(0L, target);
                        while (true) {
                            int readed = inputStream.read(buff);
                            if(readed == -1){
                                break;
                            }
                            //write buff
                            downloaded += readed;
                            publishProgress(downloaded, target);
                            if (isCancelled()) {
                                return false;
                            }
                        }
                        return downloaded == target;
                    } catch (IOException ignore) {
                        return false;
                    } finally {
                        if (inputStream != null) {
                            inputStream.close();
                        }
                    }
                } else {
                    return false;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
    
        @Override
        protected void onProgressUpdate(Long... values) {
            progressBar.setMax(values[1].intValue());
            progressBar.setProgress(values[0].intValue());
    
            textViewProgress.setText(String.format("%d / %d", values[0], values[1]));
        }
    
        @Override
        protected void onPostExecute(Boolean result) {
            textViewStatus.setText(result ? "Downloaded" : "Failed");
        }
    }
    
    0 讨论(0)
  • 2021-01-31 00:38

    You can use the okHttp receipe : Progress.java

    0 讨论(0)
  • 2021-01-31 00:38

    every time in the while loop ,you publish the progress.So it's like being blocked

    0 讨论(0)
提交回复
热议问题