0

我读过这个话题

我在下载大文件时遇到问题,因为进度对话框不上传进度或下载后只上传一次并突然显示 100%。但是当我下载小文件时,一切都很好。

我认为问题可能在这里:

publishProgress((int)(total*100/fileLength));

我的代码:

private class DownloadFile extends AsyncTask<String, Integer, String> {

    @Override

    protected String doInBackground(String... sUrl) {

        try {

            URL url = new URL(sUrl[0]);

            URLConnection connection = url.openConnection();

            connection.connect();

            // this will be useful so that you can show a typical 0-100% progress bar

            int fileLength = connection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream());

            String sdpath = Environment.getExternalStorageDirectory().getAbsolutePat();

            File dir = new File(sdpath + "/Myfolder");

            dir.mkdir();

            OutputStream output = new FileOutputStream(dir.toString() + "/" + "myfilename");

            byte data[] = new byte[1024];

            long total = 0;

            int count;

            while ((count = input.read(data)) != -1) {

                total += count;

                // publishing the progress....

               publishProgress((int)(total/fileLength)*100);

               output.write(data, 0, count);

            }
            output.flush();
            output.close();
            input.close();
            } 
          catch (Exception e) {

        }

        return null;

    }

    @Override

    protected void onPreExecute() {

        super.onPreExecute();

        mProgressDialog.show();

    }

      @Override

       protected void onProgressUpdate(Integer... progress) {

        super.onProgressUpdate(progress);

        mProgressDialog.setProgress(progress[0]);

    }

}

我的文件大约 80 MB。

4

1 回答 1

0

你应该先尝试划分:

publishProgress((int)(total/fileLength)*100);

因为你可以得到一个超出范围的划分。

于 2012-12-15T11:40:40.677 回答