如何使用两个值计算文件下载速度1.总文件大小和2.Total Bytes正在下载。
@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,如何使用这两个值计算文件下载速度。在此先感谢。
答案 0 :(得分:0)
由于您已经拥有bytes_downloaded
值,现在只需要时间维度。
bytes_downloaded / seconds taken = speed in bytes per second
如果下载10000字节花费10秒钟,则下载速度为
10000 / 10 = 1000 bps = 8 kbps
计算速度不需要总文件大小,但需要计算estimated time to completion
。
答案 1 :(得分:0)
您需要进行抽样,即拥有一个静态变量,该变量将具有下载的总字节数。对于采样,您决定使用秒,即在1000ms后检查下载的字节值。现在您需要运行一个异步任务(它将检查您下载的字节数,并在一个预定义间隔为1000毫秒的循环内执行采样工作)并且它应该以计算的速度不断更新(使用发布API)您的UI。 / p>