显示凌空文件下载的进度值

New*_*bie 8 android download android-volley

我需要以百分比显示文件下载的进度.

目前我正在使用Volley库.我使用InputStreamVolleyRequest类来发出下载请求并BufferedOutputStream读/写文件.

如何以最有效的方式显示进度更新?

Rat*_*ley -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();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您已经这样做了,那么放置进度条就很容易了。获取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();
Run Code Online (Sandbox Code Playgroud)

然后只需修改 while 循环,如下所示:

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

试试这个并让我知道。

不过,我还要告诉您,Volley 不适合大量下载。相反,我建议您使用DownloadManagerApacheHttpClient甚至AsyncTask. 它们更容易使用,并且可能更适合此目的。

  • 文件完全下载后不是会调用`onResponse`吗? (11认同)
  • 这不是正确的答案。onResponse(),我们已经下载了文件,它会显示文件写入磁盘的进度。 (6认同)