8

I have a code that download file from URL.
I have two parameters that are calculated all time for downloading :

Long start = System.nanoTime();
// downloading...
Long end = System.nanoTime();

I need to measure the estimated remaining time to the end of downloading. How I can do that?

This question (Can Java be used to determine a duration of a download?) didn't actually cover what I'm asking - I wanna know the remaining time, not the duration of downloading.

Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
  • Take the total size, subtract the already downloaded amount of data, divide it by the average download speed (you need to capture the time and progress for that). You are left with the amount of time (in seconds) you need to download that file, given that the speed is constant. – GiantTree Jun 02 '15 at 14:10
  • You need to calculate the current download speed by getting a timestamp every few seconds. Think like this: if 10 seconds have passed and I downloaded 50% of the file, how many seconds is it going to take if the speed does not change? – goncalotomas Jun 02 '15 at 14:11
  • @GiantTree you should really make this an answer. Just sayin'. – Kristy Welsh Jun 02 '15 at 14:12
  • http://stackoverflow.com/questions/3028306/download-a-file-with-android-and-showing-the-progress-in-a-progressdialog – K Neeraj Lal Jun 02 '15 at 14:12
  • @KNeerajLal you don't understand an answer. Read again. – Sergey Shustikov Jun 02 '15 at 14:12
  • Ok my bad. You need the reverse of this right? – K Neeraj Lal Jun 02 '15 at 14:15
  • I think this answer gives you the right algorithm: http://stackoverflow.com/a/799061/4867727. You just need to implement it correctly (use an `AsyncTask`, a simple loop etc.). – GiantTree Jun 02 '15 at 14:20
  • 1
    @GiantTree is correct, (And so is @Kristy-Welsh) you'll need to get your `System.nanoTime()` at specific intervals in your `onProgress()` to calculate the time remaining (as explained by @GiantTree) and report it back to your UI – Robbe Roels Jun 02 '15 at 14:22
  • @SergeyShustikov: are you asking how to do a rule of 3? – njzk2 Jun 02 '15 at 14:24

1 Answers1

14

When you start downloading save timestamp :

Long startTime = System.nanoTime();

to calculate average remaining speed :

 Long elapsedTime = System.nanoTime() - startTime;
 Long allTimeForDownloading = (elapsedTime * allBytes / downloadedBytes);
 Long remainingTime = allTimeForDownloading - elapsedTime;
Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
  • 3
    May I suggest that you do a moving average, rather than an overall average? Like, see how much data gets downloaded in 5 seconds, and base your estimate on that rate. –  Aug 27 '15 at 23:53
  • This could be written as `(allBytes / downloadedBytes - 1) * (System.nanoTime() - startTime)` – Zach May 26 '23 at 20:00