简体   繁体   English

在Android中下载文件时更新进度条

[英]update progress bar when download file in android

I try to download a file using services in android... I was able to write the program and I can download what ever I want. 我尝试使用android中的服务下载文件...我能够编写程序,并且可以下载所需文件。 but the problem is with the progress bar!!! 但是问题出在进度栏上!!! I'm not able to define the total file length (or size) and the current downloaded size. 我无法定义文件的总长度(或大小)和当前下载的大小。 I used this code to get the file lenght 我使用此代码来获取文件长度

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

and I used this part of code to define the current downloaded size 我用这部分代码定义了当前下载的大小

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

the problem is that at the end of download I got something like 241% instead of 100% (because the fileLength for ex was around 12226 and the total was 29349) Do you have any idea about this topic. 问题是,在下载结束时,我得到了241%而不是100%的信息(因为ex的fileLength大约为12226,总数为29349),您对此主题有任何想法吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM