2017-09-28 8 views
0

WebサーバーからファイルをダウンロードするのにDownloadManagerを使用しています。ダウンロードマネージャによってダウンロードされたファイルを開く

まず、DownloadManager.Requestを作成し、ヘッダーを追加し、それにデータ(タイトル、説明、通知、MimeType)を追加してエンキューします。

その後、ファイルのダウンロードが完了するまで待ってからuriを取得し、ファイルを開く予定を作成します。

選択したプログラムでファイル(PDFまたはtxt)を開く場合は、Google Pdf Viewer、HTML Viewer、Chromeなどで試してみましたが、ファイルを開くことができないと常に言います。一番上のバーで開くときDownloadManager通知があっても、ファイルは正しく開きます。デフォルトのダウンロード先は、それがためのスペースを再利用する必要がある場合、システムがあなたのファイルを削除する可能性がある共有ボリュームがあるので、

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

答えて

関連する問題