【发布时间】:2019-01-26 07:46:23
【问题描述】:
我正在尝试将 pdf 从我的应用程序打开到 Nougat 中的默认文档查看器。
这不是重复的,因为我遇到的问题与其他人不同,所以请阅读到最后。
我的尝试:
我知道我必须使用 FileProvider,制作 provider.xml,获得有关访问该应用程序的运行时权限。
在 AndroidManifest.xml
<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/provider_paths" />
</provider>
我的 GenericFileProvider
public class GenericFileProvider extends FileProvider {}
provider_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
通过这个打开pdf
val file = File(Environment.getExternalStorageDirectory().toString()+"pdfname")
val intent = Intent()
intent.action = Intent.ACTION_VIEW
val uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file)
context.grantUriPermission("com.google.android.apps.docs", uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setDataAndType(uri, "application/pdf")
context.startActivity(intent)
我的问题是:
在查看我的 pdf 时,它的第一个字符已更改。 所以它会生成文件未找到异常
当我使用此提供程序路径时。 它会删除我的 pdf 名称的第一个字符
my file name is : /storage/emulated/0on the matter of.pdf
my uri is : content://mypackage.provider/root/storage/emulated/0on%20the%20matter%20of.pdf
so pdf name is : n the matter of.pdf
当使用 provider_path 时 this 。
<root-path
name="root"
path="/" />
它将 0 添加到我的 pdf 名称中
my file name is : /storage/emulated/0on the matter of.pdf
my uri is : content://mypackage.provider/root/storage/emulated/0on%20the%20matter%20of.pdf
so pdf name is : 0on the matter of.pdf
我应该怎么做才能正确获取 pdf 名称。我应该在提供程序路径中写什么。
【问题讨论】:
-
路径不正确我认为应该是
/storage/emulated/0/on the matter of.pdf,而不是/storage/emulated/0on the matter of.pdf -
所以你可能应该使用:
val file = File(Environment.getExternalStorageDirectory().toString()+"/pdfname") -
感谢@VladyslavMatviienko 它解决了第一个字符问题,但我仍然得到
E/PdfLoader: Can't load file (doesn't open) Display Data [PDF : In the matter of Alipurduar Enterprises Ltd .pdf] +ContentOpenable, uri: content://my package.provider/external_files/In%20the%20matter%20of%20Alipurduar%20Enterprises%20Ltd.pdf -
尝试一个不带空格的文件名。
-
@greenapps 我已经尝试使用名称 abcd.pdf 但仍然得到
com.google.android.apps.docs E/DisplayData: openFd: java.io.FileNotFoundException: open failed: ENOENT for abcd.pdf。它可以从文件管理器中正确打开,但不能从我的应用程序中打开
标签: android android-studio pdf android-7.0-nougat android-fileprovider