Square的OkHttp.下载进度 [英] Square`s OkHttp. Download progress

查看:157
本文介绍了Square的OkHttp.下载进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Square的 OkHttp 时,有什么方法可以下载文件吗?

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

我在食谱中找不到任何解决方案.

I did not find any solution in Recipes.

它们具有 Call 类,该类可以异步获取内容,但是有无法获得当前进度.

They have class Call which can get content asynchronically, but there is no method to get current progress.

推荐答案

糟糕的答案很明显.对不起,愚蠢的问题.只需照常阅读InputStream.

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

这篇关于Square的OkHttp.下载进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆