广场`s OkHttp。下载进度

时间:2014-09-30 06:39:54

标签: android android-networking okhttp

使用square OkHttp时,是否有办法下载文件进度?

我在Recipes找不到任何解决方案。

他们有类Call,它可以异步获取内容,但是没有方法可以获得当前的进展。

3 个答案:

答案 0 :(得分:24)

哎哟回答显而易见。抱歉愚蠢的问题。只需像往常一样阅读InputStream。

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

答案 1 :(得分:2)

您可以使用okHttp receipe:Progress.java

答案 2 :(得分:0)

每次在while循环中,您都会发布进度。所以它就像被阻止一样