From ec8f068abc0d3fa3b14ca173afcacc1f431e36e3 Mon Sep 17 00:00:00 2001 From: daneren2005 Date: Tue, 15 Apr 2014 14:30:50 -0700 Subject: Add rate limiting for sync service downloading A background sync operation can make the system unusable as every single network operation will basically never finish until the SyncAdapter is done downloading. --- src/github/daneren2005/dsub/service/DownloadFile.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'src') diff --git a/src/github/daneren2005/dsub/service/DownloadFile.java b/src/github/daneren2005/dsub/service/DownloadFile.java index 9b7dd45d..9ddabfa4 100644 --- a/src/github/daneren2005/dsub/service/DownloadFile.java +++ b/src/github/daneren2005/dsub/service/DownloadFile.java @@ -67,6 +67,7 @@ public class DownloadFile implements BufferFile { private boolean completeWhenDone = false; private Long contentLength = null; private long currentSpeed = 0; + private boolean rateLimit = false; public DownloadFile(Context context, MusicDirectory.Entry song, boolean save) { this.context = context; @@ -150,10 +151,12 @@ public class DownloadFile implements BufferFile { } public synchronized void download() { + rateLimit = false; preDownload(); downloadTask.execute(); } public synchronized void downloadNow(MusicService musicService) { + rateLimit = true; preDownload(); downloadTask.setMusicService(musicService); try { @@ -523,6 +526,7 @@ public class DownloadFile implements BufferFile { long lastLog = System.currentTimeMillis(); long lastCount = 0; + boolean activeLimit = rateLimit; while (!isCancelled() && (n = in.read(buffer)) != -1) { out.write(buffer, 0, n); count += n; @@ -534,6 +538,21 @@ public class DownloadFile implements BufferFile { currentSpeed = lastCount / ((now - lastLog) / 1000L); lastLog = now; lastCount = 0; + + // Re-establish every few seconds whether screen is on or not + if(rateLimit) { + PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); + if(pm.isScreenOn()) { + activeLimit = true; + } else { + activeLimit = false; + } + } + } + + // If screen is on and rateLimit is true, stop downloading from exhausting bandwidth + if(activeLimit) { + Thread.sleep(10L); } } return count; -- cgit v1.2.3