【问题标题】:Opening a file downloaded by download manager打开下载管理器下载的文件
【发布时间】:2017-10-19 21:00:34
【问题描述】:

我正在使用DownloadManager 从网络服务器下载文件。

首先我创建DownloadManager.Request,向其中添加标题,向其中添加数据(标题、描述、通知、MimeType),然后将其加入队列。

之后我等到文件下载完成,获取uri,然后创建打开文件的意图。

如果我想通过选定的程序打开文件(PDF 或 txt),我尝试使用 Google Pdf Viewer、HTML Viewer、Chrome 等,它总是告诉我文件无法打开。但是,当我想通过顶部栏DownloadManager Notification 打开它时,文件会正确打开。

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));
    }
}

【问题讨论】:

    标签: java android android-download-manager download-manager


    【解决方案1】:

    好的,我通过在请求的外部公共目录中设置保存目标解决了这个问题,因为默认下载目标是共享卷,如果系统需要回收空间供系统使用,系统可能会在其中删除您的文件。 https://developer.android.com/reference/android/app/DownloadManager.Request.html

    【讨论】:

      猜你喜欢
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 2014-09-07
      • 2016-01-06
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      相关资源
      最近更新 更多