I am using the DownloadManager
to download files from a Webserver.
First I create the DownloadManager.Request
, add the headers to it, add the data to it (title, description, notification, MimeType) and then enqueue it.
After that I wait until the file finished downloading, get the uri
and then create an intent to open the file.
If I want to open the file (PDF or txt) via a chosen program, I tried with Google Pdf Viewer, HTML Viewer, Chrome and others, it always tells me the file can't be opened. When I want to open it via the top bar DownloadManager
Notification though, the file opens correctly.
public void getFileContent(Map<String, String> headers) {
if (downloadManager != null) {
DownloadManager.Request request = getRequest(headers);
Long fileId = downloadManager.enqueue(request);
compositeSubscription.add(RxDownloader.getInstance(getActivity())
.download(request)
.subscribe(path -> showFileContent(Uri.parse(path)),
throwable -> showError(throwable.getMessage())));
}
}
private DownloadManager.Request getRequest(Map<String, String> headers) {
Uri uri = Uri.parse(BuildConfig.API_URL + "api/v2/files/" + fileResource.getId() + "/raw");
DownloadManager.Request request = new DownloadManager.Request(uri);
request = addRequestHeaders(request, headers);
request = setRequestData(request);
return request;
}
private DownloadManager.Request addRequestHeaders(DownloadManager.Request request, Map<String, String> headers) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
request.addRequestHeader(entry.getKey(), entry.getValue());
}
return request;
}
private DownloadManager.Request setRequestData(DownloadManager.Request request) {
request.setTitle(getString(R.string.file_downloader));
request.setDescription(String.format(getString(R.string.fmt_downloading), fileResource.getFileName()));
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setMimeType(fileResource.getMimeType());
return request;
}
private void showFileContent(Uri uri) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(uri, fileResource.getMimeType());
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, getString(R.string.open_file));
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
showError(getString(R.string.no_application_installed));
}
}
Ok, I solved the problem by setting a saving destination in the external public dir for the request, since the default download destination is a shared volume where the system might delete your file if it needs to reclaim space for system use. https://developer.android.com/reference/android/app/DownloadManager.Request.html