繁体   English   中英

使用Android Intent打开PDF文件

[英]Opening PDF file using Android intent

所以这是场景:

我正在从网络下载PDF并将其保存在/0/Download/NSIT - Notices/"fileName".pdf

现在像这样发送Intent:

private void openPDF(String fileName) {
    Log.d(TAG, "openPDF: called");
    Intent intent = new Intent(Intent.ACTION_VIEW);File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download", "NSIT - Notices");
    File myPDF = new File(Environment.getExternalStorageDirectory() + "/Download/NSIT - Notices", fileName + ".pdf");
    Uri uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", myPDF);
    Log.d(TAG, "openPDF: intent with uri: " + uri);
    intent.setDataAndType(uri, "application/pdf");
    context.startActivity(Intent.createChooser(intent, "Open with..."));
}

现在,任何PDF阅读器(Google Drive PDF阅读器,System PDF Viewer)都在说

The File Does Not Exist

图片: 在此处输入图片说明

Google坐着不做任何事(这就是为什么不包括其图片)

Mainfest.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>

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>

我在AsyncTask中在此处创建文件,但从该AsyncTask的postExecute打开

File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download", "NSIT - Notices");
            File myPDF = new File(myDir, params[1] + ".pdf");
            if (!myDir.exists())
                myDir.mkdirs();
            try {
                fileOutputStream = new FileOutputStream(myPDF);
                fileOutputStream.write(response.bodyAsBytes());
                fileOutputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.d(TAG, "doInBackground: Download complete");

logcat的

在此处输入图片说明

以前它是抛出FileUriExposedException然后我使用此FileProvider 问题是我的应用下载的pdf文件已成功创建,我可以从任何文件管理器(现在为ES File Explorer)成功打开它,但无法从我的应用中打开它:(。我是FileProvider 。需要帮助!

PS:那也不是我的设备问题。 使用其他两款具有不同ROM和API> = 23的手机进行了测试

请设置intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

它将把您文件的访问权限授予其他提供商

请参阅文件提供程序的文档

内容提供程序是否可供其他应用程序使用:

true:提供程序可用于其他应用程序。 任何应用程序都可以使用提供者的内容URI来访问它,但要遵守为提供者指定的权限。

false:该提供程序不可用于其他应用程序。 访问您的应用程序的提供程序。 只有具有与提供者相同的用户ID(UID)的应用程序才可以访问它。

尝试更改android:exported =“ true”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM