安卓下载管理器文件大小不正确



我正在使用下载管理器下载文件。为了显示下载进度,我需要文件大小。当我使用以下代码时,我得到的文件大小为 -1。如何获得正确的文件大小?

DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadmanagerid1);
Cursor cursor = dm.query(q);
if (cursor.moveToFirst()) {
FileDownloading.setDownload_status(cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)));
long fileSize = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
long bytesDL = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
Log.e("file size getting ",""+fileSize);    
FileDownloading.setDownload_progress((int) ((bytesDL * 100.0f) / fileSize));
}
else {
FileDownloading.setDownload_progress(0);
FileDownloading.setDownload_status(-1);
}
cursor.close();
有时,

您尝试下载的下载链接将无法访问获取大小,最终会将文件大小显示为"-1"。

我建议尝试来自 https://file-examples.com/的链接,MP3和MP4链接运行良好。

这样做:

while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
               // publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                // writing data to file
                progressBar.setProgress((int) ((total * 100) / lenghtOfFile));
                output.write(data, 0, count);
            }

最新更新