【发布时间】:2018-06-30 16:44:48
【问题描述】:
我想使用 Android 的 DownloadManager 下载 pdf,然后让用户使用他的 pdf 查看器应用程序打开它。
为此,我正在使用以下方法保存启动下载:
public String downloadFile(String url, String name) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Downloading file: " + name);
request.setTitle("My app name");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setMimeType("application/pdf");
Uri destinationUri = Uri.fromFile(new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), name+".pdf"));
request.setDestinationUri(destinationUri);
manager.enqueue(request);
return destinationUri.toString();
}
我正在保存 Uri 并使用它使用 PDF 视图应用程序打开 PDF,如下所示:
public void openDownloadedFile(String uri) {
Intent intent = new Intent(Intent.ACTION_VIEW);
File file = new File(uri);
Uri uriForFile = FileProvider.getUriForFile(context.getApplicationContext(), context.getString(R.string.my_file_authority), file);
intent.setDataAndType(uriForFile, "application/pdf");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
context.startActivity(intent);
}
我的application 的清单文件包含以下提供程序:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="@string/my_file_authority"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
而且我在provider_paths中也有如下内容:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path
name="my_pdfs"
path="."/>
<external-path
name="my_pdfs"
path="."/>
<files-path
name="my_pdfs"
path="."/>
</paths>
我知道那里有 2 个额外的元素,但我只是想确保我不会错过任何东西。
很遗憾,这会崩溃,原因如下:
java.lang.IllegalArgumentException: Failed to find configured root that contains /file:/storage/emulated/0/Android/data/{my_app_id}/files/Download/filename_of_pdf.pdf
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:738)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:417)
一些额外的细节:
minSdkVersion 21
targetSdkVersion 27
我正在使用 Android O 在三星 S8 和 Android 模拟器上进行测试。
有人可以告诉我为什么会这样吗? 我怎么知道 Android 正在考虑我的 provider_paths?
谢谢!
PS:
- 我尝试为 DownloadManager 使用外部公共目录,但它崩溃了,说它没有权限,即使在我的清单中我确实有 WRITE_EXTERNAL_STORAGE 权限并且我请求用户的权限,但对话框没有出现.
- 我也替换了“.”从带有“下载”或“Android”甚至“Android/data/{my_app_id}/files/Download/”的provider_paths.xml文件中,但我遇到了同样的崩溃
【问题讨论】:
标签: android android-download-manager android-fileprovider