Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

Commit

Permalink
Keep downloads update thread paused when there aren't active downloads (
Browse files Browse the repository at this point in the history
  • Loading branch information
MortimerGoro authored Apr 27, 2020
1 parent 1fe893a commit 32305d7
Showing 1 changed file with 26 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.webkit.URLUtil;

import androidx.annotation.NonNull;
Expand All @@ -21,6 +22,7 @@
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

Expand All @@ -41,6 +43,7 @@ default void onDownloadError(@NonNull String error, @NonNull String file) {}
private List<DownloadsListener> mListeners;
private DownloadManager mDownloadManager;
private ScheduledThreadPoolExecutor mExecutor;
private ScheduledFuture<?> mFuture;

public DownloadsManager(@NonNull Context context) {
mMainHandler = new Handler(Looper.getMainLooper());
Expand All @@ -67,14 +70,29 @@ public void end() {
public void addListener(@NonNull DownloadsListener listener) {
mListeners.add(listener);
if (mListeners.size() == 1) {
mExecutor.scheduleAtFixedRate(mDownloadUpdateTask, 0, REFRESH_INTERVAL, TimeUnit.MILLISECONDS);
scheduleUpdates();
}
}

public void removeListener(@NonNull DownloadsListener listener) {
mListeners.remove(listener);
if (mListeners.size() == 0) {
mExecutor.remove(mDownloadUpdateTask);
stopUpdates();
}
}

private void scheduleUpdates() {
if (mFuture != null) {
// Already scheduled
return;
}
mFuture = mExecutor.scheduleAtFixedRate(mDownloadUpdateTask, 0, REFRESH_INTERVAL, TimeUnit.MILLISECONDS);
}

private void stopUpdates() {
if (mFuture != null) {
mFuture.cancel(true);
mFuture = null;
}
}

Expand Down Expand Up @@ -104,6 +122,7 @@ public void startDownload(@NonNull DownloadJob job) {
}

mDownloadManager.enqueue(request);
scheduleUpdates();
}

@Nullable
Expand Down Expand Up @@ -192,7 +211,12 @@ public void onReceive(Context context, Intent intent) {

private void notifyDownloadsUpdate() {
List<Download> downloads = getDownloads();
int filter = Download.RUNNING | Download.PAUSED | Download.PENDING;
boolean activeDownloads = downloads.stream().filter(d -> (d.getStatus() & filter) != 0).count() > 0;
mListeners.forEach(listener -> listener.onDownloadsUpdate(downloads));
if (!activeDownloads) {
stopUpdates();
}
}

private void notifyDownloadCompleted(@NonNull Download download) {
Expand Down

0 comments on commit 32305d7

Please sign in to comment.