gpt4 book ai didi

java - 如何使用 bytes_downloaded 和 bytes_total Android/Java 测量下载速度

转载 作者:太空宇宙 更新时间:2023-11-04 14:16:27 25 4
gpt4 key购买 nike

如何使用两个值 1.总文件大小和 2.下载的总字节数来计算文件下载速度。

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.start_ed) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(durl));
request.setTitle("File Download");
request.setDescription("file is being download");

request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String nof = URLUtil.guessFileName(durl, null,
MimeTypeMap.getFileExtensionFromUrl(durl));

request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, nof);

final DownloadManager downloadManager = (DownloadManager) MainActivity.this
.getSystemService(Context.DOWNLOAD_SERVICE);
// long id = downloadManager.enqueue(request); //This is to get the
// id of the download.
final long download_id = downloadManager.enqueue(request);

final ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
final TextView current_tvm = (TextView) findViewById(R.id.current_tv);
final TextView totl_tv = (TextView) findViewById(R.id.totalsize);
new Thread(new Runnable() {

@Override
public void run() {

boolean downloading = true;

while (downloading) {

DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(download_id);

Cursor cursor = downloadManager.query(q);
cursor.moveToFirst();
final int bytes_downloaded = cursor.getInt(cursor
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
final int bytes_total = cursor.getInt(cursor
.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
if (cursor.getInt(cursor
.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false;
}
final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);

runOnUiThread(new Runnable() {

@Override
public void run() {
// totl_tv.setText(bytes_total);
// current_tvm.setText(bytes_downloaded);
String i = android.text.format.Formatter
.formatFileSize(MainActivity.this,
bytes_downloaded);

System.out.println(i);
current_tvm.setText(i);
mProgressBar.setProgress((int) dl_progress);

}
});

// Log.d(Constants.MAIN_VIEW_ACTIVITY,
// statusMessage(cursor));
cursor.close();
}

}
}).start();

}
}

现在我有一个文件的两个值 bytes_downloaded 和 bytes_total,如何使用这两个值计算文件下载速度。提前致谢。

最佳答案

由于您已经有了 bytes_downloaded 值,因此您现在需要的只是时间维度。

bytes_downloaded / seconds taken = speed in bytes per second 

如果下载 10000 字节需要 10 秒,您的下载速度将为

10000 / 10 = 1000 bps = 8 kbps

计算速度不需要总文件大小,但是需要计算预计完成时间

关于java - 如何使用 bytes_downloaded 和 bytes_total Android/Java 测量下载速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27664684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com