Set progressbar to KB and MB instead of % for android download manager

淺唱寂寞╮ 提交于 2019-12-22 17:46:15

问题


I'm trying to download an image from url and I need to display the size of the file and the progress of the file downloading.

This is what I have.

 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)

If I set it to mProgressDialog.setProgressNumberFormat("%1d kb / %2d kB") its showing as 1kb of 100kb but unable to get the actual size of the file which I'm trying to download

I need it display as 1.2MB/3.6MB

Issue is the progress is displaying as seen below 60/100 but I don't want that


回答1:


Finally made it to work:

Here is the way

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;

and set this to progressbar

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

Method: Converting byte to string

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)";
        }

  }


来源:https://stackoverflow.com/questions/35918197/set-progressbar-to-kb-and-mb-instead-of-for-android-download-manager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!