显示Volley文件下载进度值

9
我需要显示文件下载的进度百分比。 目前我正在使用Volley库。 我使用InputStreamVolleyRequest类进行下载请求,并使用BufferedOutputStream读取/写入文件。 如何以最有效的方式显示进度更新?
2个回答

0

1
这并没有回答原问题。 - Alberto M

-1

正如您所提到的,您正在使用InputStreamVolleyRequest,我希望您已经编写了以下代码或类似的代码:

@Override
public void onResponse(byte[] response) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    try {
        if (response!=null) {

            String content =request.responseHeaders.get("Content-Disposition")
                    .toString();
            StringTokenizer st = new StringTokenizer(content, "=");
            String[] arrTag = st.toArray();

            String filename = arrTag[1];
            filename = filename.replace(":", ".");
            Log.d("DEBUG::FILE NAME", filename);

            try{
                long lenghtOfFile = response.length;

                InputStream input = new ByteArrayInputStream(response);

                File path = Environment.getExternalStorageDirectory();
                File file = new File(path, filename);
                map.put("resume_path", file.toString());
                BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(file));
                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    output.write(data, 0, count);
                }

                output.flush();

                output.close();
                input.close();
            }catch(IOException e){
                e.printStackTrace();

            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

如果您已经完成了这个步骤,那么添加一个进度条就很容易了。 获取ProgressDialog对象并按照下面所示进行初始化:
progressDialog = new ProgressDialog(Activity Context here);
progressDialog.setTitle("Any Title here");
progressDialog.setMessage("Downloading in Progress...");
progressDialog.setProgressStyle(progressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.setMax(100);
progressDialog.setProgress(0);
progressDialog.show();

然后只需按照下面所示修改while循环:

while ((count = input.read(data)) != -1) {
    total += count;
    output.write(data, 0, count);
    progress = (int)total*100/file_length;
    progressDialog.setProgress(progress);
}

试试这个,然后告诉我。

但是我也要告诉你,Volley不适合大量下载。相反,我建议你使用DownloadManager或Apache的HttpClient甚至是AsyncTask。它们更容易使用,对于这个目的可能更好。


11
onResponse 方法不是在文件下载完成后才被调用吗? - Cerlin
1
是的,事实上这在我的端上不起作用。另外,InputStreamVolleyRequest类是从一个示例中获取的,该示例在问题或答案中都没有提到。 - Alberto M
6
这不是正确答案。在onResponse()中,我们已经下载了文件,它会显示文件写入磁盘的进度。 - jee
Volley 在网络波动的情况下支持断点续传吗? - Paras Sidhu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接