android - 为 android 下载管理器将进度条设置为 KB 和 MB 而不是 %

标签 android progress-bar progressdialog filesize

我正在尝试从 url 下载图像,我需要显示文件的大小和文件下载的进度。

这就是我的。

 int bytes_downloaded = cursor.getInt(cursor
                        .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

 final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total);
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        getFileSize(fileSizeInKB);
                        mProgressDialog.setProgress((int) dl_progress);

                    }
  });

As of now its showing %(ie..10/100)

如果我将它设置为 mProgressDialog.setProgressNumberFormat("%1d kb/%2d kB") 它显示为 1kb of 100kb 但无法获取我尝试下载的文件的实际大小

我需要它显示为 1.2MB/3.6MB

问题是进度显示低于 60/100,但我不希望这样

enter image description here

最佳答案

终于成功了:

方法是这样的

long  downloadedsize, filesize;
public static final double SPACE_KB = 1024;
public static final double SPACE_MB = 1024 * SPACE_KB;
public static final double SPACE_GB = 1024 * SPACE_MB;
public static final double SPACE_TB = 1024 * SPACE_GB;

并将其设置为进度条

mProgressDialog.setProgressNumberFormat((bytes2String(downloadedsize)) + "/" + (bytes2String(filesize)));

方法:字节转字符串

public static String bytes2String(long sizeInBytes) {

        NumberFormat nf = new DecimalFormat();
        nf.setMaximumFractionDigits(2);

        try {
            if ( sizeInBytes < SPACE_KB ) {
                return nf.format(sizeInBytes) + " Byte(s)";
            } else if ( sizeInBytes < SPACE_MB ) {
                return nf.format(sizeInBytes/SPACE_KB) + " KB";
            } else if ( sizeInBytes < SPACE_GB ) {
                return nf.format(sizeInBytes/SPACE_MB) + " MB";
            } else if ( sizeInBytes < SPACE_TB ) {
                return nf.format(sizeInBytes/SPACE_GB) + " GB";
            } else {
                return nf.format(sizeInBytes/SPACE_TB) + " TB";
            }
        } catch (Exception e) {
            return sizeInBytes + " Byte(s)";
        }

  }

关于android - 为 android 下载管理器将进度条设置为 KB 和 MB 而不是 %,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35918197/

相关文章:

java - Android 中 OffsetDateTime.now() 的奇怪行为

android - SoapFault - 错误代码 : 'soap:Client' faultstring: 'System. Web.Services.Protocols.SoapException

android - 我找不到标签 fragment

java - Android - 创建进度对话框

java - 显示导入数据库的进度对话框

Java/Android Edittext.gettext().toString 不工作

用于文件上传的 Django Modelform 进度条

python - tqdm可以嵌入html吗?

java - 从进度对话框中删除背景

multithreading - 在等待线程完成时显示 progressDialog 2 秒