无法打开内部存储器中的PDF以使用File Provider在Android 8和9上查看 [英] Unable to open PDF from internal storage for viewing on Android 8 and 9 using File Provider

查看:287
本文介绍了无法打开内部存储器中的PDF以使用File Provider在Android 8和9上查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅适用于Android 8和9。

For Android 8 and 9 only.

我在这里有PDF归档器-

I have a PDF filer here -

String url = "file:///storage/emulated/0/Android/data/com.verna.poc/files/Download/mypdf.pdf";

我正在尝试使用此文件打开该文件以供查看-

I'm trying to open this file for viewing using this -

File file= new File(url);
file.setReadable(true, false);

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri pdfUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file);
intent.setDataAndType(pdfUri, "application/pdf");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

List<ResolveInfo> resInfoList = getApplicationContext().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    for (ResolveInfo resolveInfo : resInfoList) {
        String packageName = resolveInfo.activityInfo.packageName;
        getApplicationContext().grantUriPermission(packageName, pdfUri,
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }

Intent in = Intent.createChooser(intent, "Open File");
startActivity(in);

文件选择器选项正在打开,当我使用Google PDF阅读器打开文件时,PDF阅读器将打开并立即关闭。我的代码有什么问题?

The File chooser option is opening and when I open the file using Google PDF reader, the PDF reader opens and closes immediately. Whats wrong in my code ?

推荐答案

您正在尝试与另一个应用共享内部存储中的文件。您将需要创建一个文件提供程序才能正常工作。您将需要指定一个目录,希望文件提供程序为该目录生成Uris

You are trying to share a file from internal storage with the another app. You will need to create a file provider for this to work. You will need to specify a directory which you want the file provider to generate Uris for


FileProvider是ContentProvider的特殊子类,可促进安全共享通过为文件创建content:// Uri而不是file:/// Uri来与应用程序关联的文件。

FileProvider is a special subclass of ContentProvider that facilitates secure sharing of files associated with an app by creating a content:// Uri for a file instead of a file:/// Uri.

FileProvider只能生成内容URI用于您预先指定的目录中的文件。要指定目录,请使用元素的子元素以XML格式指定其存储区域和路径。例如,以下path元素告诉FileProvider,您打算为私有文件区域的images /子目录请求内容URI。

A FileProvider can only generate a content URI for files in directories that you specify beforehand. To specify a directory, specify the its storage area and path in XML, using child elements of the element. For example, the following paths element tells FileProvider that you intend to request content URIs for the images/ subdirectory of your private file area.

这个答案对此有一个很好的例子

This answer has a good example on this

链接

这是 FileProvider

FileProvider

这篇关于无法打开内部存储器中的PDF以使用File Provider在Android 8和9上查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆