【问题标题】:Unable to open file using FileProvider无法使用 FileProvider 打开文件
【发布时间】:2020-04-28 10:58:38
【问题描述】:

我希望从下载文件夹 (/storage/emulated/0/Download) 打开一个文件,这是我的代码
我先检查文件是否存在

File file = new File("/storage/emulated/0/Download" + File.separator + <file-name> + ".pdf");
                if(file.exists()) {
                    openfile("/storage/emulated/0/Download" + File.separator + <file-name> + ".pdf");
                    Log.d("upload", "onClick: already exists");
                }
                else {
                    downloadfile(Url);
                    Log.d("upload", "onClick: download");
                }

如果文件存在,我使用此代码打开文件

public void openfile(String path){
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID+".provider",new File(path));
    intent.setDataAndType(uri, "application/pdf");
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    intent.addFlags(Intent.EXTRA_STREAM,uri);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    context.startActivity(Intent.createChooser(intent,"Choose an application"));
}

这是我的清单

<provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/path"/>
    </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>

When I click to open the file it shows intent chooser and when drive pdf viewer is selected it opens up with a blank screen and closes immediately and when any other app is chosen then it shows error File not found(content:// (包名).provider/storage%2Femulated%2F0/Download/file-name.pdf)。我不知道我做错了什么。

【问题讨论】:

  • If t the file exists... 使用 File:exists() 确定文件是否存在。
  • new File(path) 您应该在代码中显示path 的使用值。
  • name="storage/emulated/0" 使用不带斜线的名称。
  • @blackapps 我已经进行了您提到的更改,但结果仍然相同,至于路径,提到了调用函数的位置
  • 你应该使用 Intent.EXTRA_STREAM 作为你的 uri。

标签: android file android-studio android-fileprovider android-storage


【解决方案1】:

也许不会

intent.addFlags(Intent.EXTRA_STREAM,uri);

但是

intent.putExtra(Intent.EXTRA_STREAM, uri)

?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 2020-10-05
    • 2017-08-23
    • 2017-02-21
    • 1970-01-01
    • 2019-07-17
    • 2019-01-06
    相关资源
    最近更新 更多