我正在创建一个PDF文件并将其保存在本地存储中。当试图打开它时,它在除了Android N之外的所有设备中都是完美的。我可以使用FileProvider在Android N中打开PDF文件,但它显示为空白。
这是我的URI
content://com.products.provider/external_storage_root/Android/data/com.products/in_17052017_170502_1_1001.pdf
这是我的代码
Uri path;
File pdfFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/"
+ "Android" + "/" + "data" + "/" + "com.products" + "/" + file);
if (Build.VERSION.SDK_INT >= 24) {
path = FileProvider.getUriForFile(getActivity(), "com.products.provider", pdfFile);
} else {
path = Uri.fromFile(pdfFile);
}
// Setting the intent for pdf reader
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path, "application/pdf");
pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivity(pdfIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "Can't read pdf file", Toast.LENGTH_SHORT).show();
}
答案 0 :(得分:35)
问题在于你如何在意图
上设置标志pdfIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
相反,试试这个:
pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
pdfIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
答案 1 :(得分:6)
Grzegorz Matyszczak的解决方案适用于我的案例。我和Sabya Sachi的设置非常相似。更具体地说,这一行允许我看到PDF文件(来自FileProvider.getURIForFile调用的URI):
fstream
#include <fstream>
int main()
{
std::ofstream("/tmp/test.txt").flush() << "hello"
<< " ... OK, this now works too\n";
}
pdfIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
下的grantUriPermissions
here的更多信息。
答案 2 :(得分:3)
我可以看到您已将FileProvider
用于Nougat。
您必须在AndroidManifest.xml中添加FileProvider标记。
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
</provider>
FileProvider只能为您事先指定的目录中的文件生成内容URI。要将此文件链接到FileProvider,请添加元素作为定义FileProvider的元素的子元素。
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths"/>
</provider>
您必须为每个目录指定一个子元素,该目录包含您想要内容URI的文件。您可以将它们添加到名为res/xml/file_paths.xml
的新文件中。例如,这些XML元素指定了两个目录:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<files-path name="my_images" path="images/"/>
<files-path name="my_docs" path="docs/"/>
</paths>
- &gt;您必须在file_paths.xml
有关详细信息,请参阅this
答案 3 :(得分:0)
path = MyFileProvider.getUriForFile(getActivity(), "com.products.provider", pdfFile);
其中MyFileProvider
应该是扩展FileProvider
的通用类:
public class MyFileProvider extends FileProvider {
}
android:name
部分中的MyFileProvider类位置设置为provider
属性来修改AndroidManifest:android:name=".utils.MyFileProvider"