视频下载进度的百分比计算

时间:2014-05-06 13:19:13

标签: android progressdialog

我正在使用Intent服务成功下载视频。但是我无法显示下载的进度。

resultData.putInt("progress" ,(int) (total * 100 / fileLength));

这里,我遇到的问题是,因为fileLength是一个整数,我的文件长度远远超过整数容量。我试了很长时间,仍然无法工作。

我知道Java中的Big Integers,但我认为我没有看到更明显的答案。

编辑:

这是代码,我使用意图服务来运行下载并通过接收器更新对话框。

public void  onHandleIntent(Intent intent) {
     String urlToDownload       = intent.getStringExtra("url");
     String path                = intent.getExtras().getString(C.INTENT_VIDEO_PATH);
     String videoId             = intent.getExtras().getString(C.INTENT_VIDEO_ID);
     L.i("Path : "+path);
     ResultReceiver receiver    = (ResultReceiver) intent.getParcelableExtra("receiver");
        try {
            URL url = new URL(urlToDownload);
            URLConnection connection = url.openConnection();
            connection.connect();

            long fileLength = connection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(path);


            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                Bundle resultData = new Bundle();
                resultData.putInt("progress" ,(int) (total * 100 / fileLength));
                receiver.send(UPDATE_PROGRESS, resultData);
                output.write(data, 0, count);
            }
            L.i("Total :"+count);

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

        //TODO: Update DB.

        VideoTable.updateVideoPath(videoId, path);
        Bundle resultData = new Bundle();
        resultData.putInt("progress" ,100);
        receiver.send(UPDATE_PROGRESS, resultData);

}

1 个答案:

答案 0 :(得分:0)

记住:

8 Bit = 1 Byte
1024 Byte = 1 Kbyte
1024 KByte = 1 MegaByte
1024 MByte = 1 GigaByte
1024 GByte = 1 TeraByte
1024 Terabytes = 1 Petabyte

我希望它可以帮到你

在java,file.length()中,该方法返回由此抽象路径名表示的文件的长度(以字节为单位)。