在android下载文件时更新进度条

问题描述 投票:0回答:1

我尝试使用android中的服务下载文件...我能够编写程序,我可以下载我想要的东西。但问题是进度条!!!我无法定义总文件长度(或大小)和当前下载的大小。我用这段代码来获取文件长度

            URL url = new URL(urlToDownload);
            URLConnection connection = url.openConnection();
            connection.connect();
            int fileLength = connection.getContentLength();

我用这部分代码来定义当前的下载大小

           InputStream input = new BufferedInputStream(connection.getInputStream());
           OutputStream output = new FileOutputStream("/sdcard/BarcodeScanner-debug.apk");

           byte data[] = new byte[1024];
           long total = 0;
           int count;
           while ((count = input.read(data)) != -1) {
               total += count;
               int currentValue=(total * 100 / fileLength);
               output.write(data, 0, count);
           }

问题是,在下载结束时,我得到了241%而不是100%的东西(因为前面的fileLength大约是12226,总数是29349)你对这个话题有任何想法。

java android download progress-bar progress
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.