Last active
March 11, 2018 12:44
-
-
Save wightwulf1944/cc97579b6d9e22bec5d3121f56ff82fc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DownloadManager implements Closeable { | |
private static final int MAX_TRIES = 3; | |
private final Realm realm = Realm.getDefaultInstance(); | |
@Override | |
public void close() { | |
realm.close(); | |
} | |
public void addToQueue(Book book) { | |
realm.beginTransaction(); | |
DownloadTask task = realm.createObject(DownloadTask.class); | |
task.setBook(book); | |
realm.commitTransaction(); | |
} | |
public Iterable<DownloadTask> getQueued() { | |
return realm.where(DownloadTask.class) | |
.equalTo("status", QUEUED) | |
.findAll(); | |
} | |
public void notifyRunning(DownloadTask task) { | |
realm.beginTransaction(); | |
task.setStatus(RUNNING); | |
realm.commitTransaction(); | |
} | |
public void notifyDone(DownloadTask task) { | |
realm.beginTransaction(); | |
task.setStatus(DONE); | |
// FIXME | |
task.getBook().setDownloaded(true); | |
realm.commitTransaction(); | |
} | |
public void notifyFailed(DownloadTask task) { | |
realm.beginTransaction(); | |
if (task.getTries() < MAX_TRIES) { | |
task.incrementTries(); | |
task.setStatus(QUEUED); | |
} else { | |
task.setStatus(FAILED); | |
} | |
realm.commitTransaction(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Override | |
protected void onHandleIntent(@Nullable Intent intent) { | |
DownloadManager downloadManager = new DownloadManager(); | |
for (DownloadTask task : downloadManager.getQueued()) { | |
downloadManager.notifyRunning(task); | |
Book book = task.getBook(); | |
try { | |
downloadBook(book); | |
downloadManager.notifyDone(task); | |
Timber.w("Book successfully downloaded: %s", book.getId()); | |
} catch (Exception e) { | |
downloadManager.notifyFailed(task); | |
Timber.w(e, "Failed to download book: %s", book.getId()); | |
} | |
} | |
downloadManager.close(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment