簡體   English   中英

打開由下載管理器下載的文件

[英]Opening a file downloaded by download manager

我正在使用DownloadManager從Web服務器下載文件。

首先,我創建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));
    }
}

好的,我通過在請求的外部公共目錄中設置保存目標來解決了該問題,因為默認的下載目標是共享卷,如果需要回收空間以供系統使用,系統可能會刪除您的文件。 https://developer.android.com/reference/android/app/DownloadManager.Request.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM