首页 > 解决方案 > 如何在 Andriod 中使用绝对路径文件共享 pdf 文件

问题描述

我如何在 android 中共享 pdf 文件我可以使用绝对路径文件中的 pdfView 库查看 pdf,所以我认为路径是正确的,但无法使用用于查看 pdf 的相同路径共享,我还尝试使用 toast 查看给出正确路径的路径,但是当我尝试共享文件时,应用程序崩溃在这里是正在使用的代码

Uri uri = Uri.fromFile(new File(arrayList.get(i).getAbsolutePath()));
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("application/pdf");

            intent.putExtra(Intent.EXTRA_SUBJECT, "");
            intent.putExtra(Intent.EXTRA_TEXT, "");
            intent.putExtra(Intent.EXTRA_STREAM, uri);

            try {
                activity.startActivity(Intent.createChooser(intent, "Share Via"));
            } catch (ActivityNotFoundException e) {
                Toast.makeText(activity, "No Sharing App Found", Toast.LENGTH_SHORT).show();
            }
``

标签: androidandroid-intentandroid-sharing

解决方案


所以这是最终的解决方案

首先,这会在您的应用程序的结束标记之前进入清单

        <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/provider_paths"/>
        </provider>

然后在您的 res 文件夹中创建一个 xml 资源目录,然后创建您在清单中指定的文件,即provider_paths在文件中的 this 过去

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>

然后最后在您的实际代码中执行此操作

Uri uri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", new File(pdf_list.get(i).getAbsolutePath()));
            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("application/pdf");

            intent.putExtra(Intent.EXTRA_SUBJECT, "");
            intent.putExtra(Intent.EXTRA_TEXT, "");
            intent.putExtra(Intent.EXTRA_STREAM, uri);

            try {
                activity.startActivity(Intent.createChooser(intent, "Share Via"));
            } catch (ActivityNotFoundException e) {
                Toast.makeText(activity, "No Sharing App Found", Toast.LENGTH_SHORT).show();
            }

推荐阅读