3

I tried to get the file from the server using the Android downloadManager and I confirmed that it works properly.

but, the COLUMN_BYTES_DOWNLOADED_SO_FAR value changes about every 1 to 2 seconds, so the program bar does not increase smoothly. Is there any way to modify the update interval?

boolean downloading = true;
int oldProgressValue = 0;
int lastProgressValue = 0;
long startTime = System.currentTimeMillis();

try {
    while (downloading) {
        DownloadManager.Query q = new DownloadManager.Query();
        q.setFilterById(downloadId);
        Cursor cursor = downloadManager.query(q);
        cursor.moveToFirst();
        int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

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

        if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
            downloading = false;
        }

        //0 ~ 100
        lastProgressValue = (int) ((bytes_downloaded * 100l) / bytes_total);

        Thread.sleep(50);

        if (timeOut > 0) {
            downloading = UpdateTimeOut(startTime, oldProgressValue, lastProgressValue);
        }

        if (oldProgressValue != lastProgressValue) {
            oldProgressValue = lastProgressValue;
            int finalOldProgressValue = oldProgressValue;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textView.setText(String.valueOf(finalOldProgressValue));
                }
            });
        }
        cursor.close();
    }
} catch (InterruptedException e) {
    e.printStackTrace();
} finally {

}

Additionally

Android Download Manager with progress dialog

Same question and I tried as answer but it didn't solve.

Android DownloadManager Progress

I also applied the answer to the question, but didn't get the updated value.

1 Answers1

0

I had the same issue, what I did is to call this method that sets a ValueAnimator every time that the COLUMN_BYTES_DOWNLOADED_SO_FAR changes and that made it look smooth

   private fun updateProgressBar(progress: Int){
     runOnUiThread {
        val progressAnimator = ValueAnimator.ofFloat(pb_download_video.progress.toFloat(), progress.toFloat())
        progressAnimator.duration = 300
        progressAnimator.addUpdateListener {
            val value: Int = (it.animatedValue as Float).toInt()
            binding.pbDownloadVideo.progress = value
        }
        progressAnimator.doOnEnd { if (progress == 100) // action when is done loading }
        progressAnimator.start()
    }
}
max
  • 443
  • 7
  • 13