I have an IntentService
which represents one task in the download queue. I receive the data to download from an Intent
in onHandleIntent(Intent)
method.
I am using retrofit 2 for download. In my app you have larger media files. For this reason, I want to use @Streaming
annotation. When I do, the app freeze till the download is finished. I tried to wrap the code in a Thread
but it did not help. When I don't use @Streaming
than I can browse the app while the download is in progress. This however uses a lot of memory in because of the large ResponseBody
.
@Streaming
@GET
Call<ResponseBody> downloadMediaFile(@Url String directDownload);
Service:
@Override
protected void onHandleIntent(Intent intent) {
if(intent != null && intent.hasExtra(DownloadManager.EXTRA_MEDIA)){
final Media media = intent.getParcelableExtra(DownloadManager.EXTRA_MEDIA);
FeedService feedService = ApiServices.get().getFeedService();
String url = media.getDirectDownload();
Call<ResponseBody> call = feedService.downloadMediaFile(url);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
File resultFile = response.isSuccessful() ? writeResponse(response.body(), media) : null;
LogUtils.LOGD(TAG, resultFile != null ? "Download successful" : "Download unsuccessful");
if(resultFile != null){
EventBus.getDefault().post(new MediaDownloadComplete(media, resultFile));
} else {
onFailure(call, new NullPointerException("No result file received"));
}
if(DownloadManager.get() != null){
DownloadManager.get().nextInQueue();
}
media.setInProgress(false);
stopSelf();
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
media.setInProgress(false);
stopSelf();
}
});
}
}
DownloadManager
is a Service
which handles the download queue.