Warm tip: This article is reproduced from serverfault.com, please click

其他-使用Android 10在pdf应用程序上显示pdf文件时出现问题

(其他 - Problems displaying pdf files on pdf apps using Android 10)

发布于 2020-11-24 22:35:23

我一直想显示一个pdf文件,选择在我的Android 10手机上安装的一些pdf应用程序。这是我正在使用的代码:

活动

        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/sample.pdf");

                    if(file.exists()) {

                        Uri path = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", file);

                        this.grantUriPermission(this.getPackageName(), path, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
                        pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                        pdfOpenintent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


                        pdfOpenintent.setDataAndType(path, "application/pdf");


                        try {
                           // ((Activity) ctx).startActivityForResult(pdfOpenintent, 6);
                           this.startActivity(pdfOpenintent);
                        } catch (ActivityNotFoundException e) {

                        }
                    }  else
                        Toast.makeText(this, "No file found" , Toast.LENGTH_LONG).show();

Android清单


    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.VIBRATE" />

........


        <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_paths

<?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应用程序时,其中一些崩溃了;如果选择“驱动器pdf查看器”,它会显示文件名,但屏幕变黑,因此我认为我无法以正确的方式打开pdf应用程序。

正如你在“活动”中看到的那样,我放置了几个标志,因为新的android版本似乎需要某种权限才能访问内部存储。

Questioner
user14702307
Viewed
11
user14702307 2020-12-01 21:35:44

问题解决了。该代码应根据以下链接放在清单上

<!-- This attribute is "false" by default on apps targeting
     Android 10 or higher. -->
  <application android:requestLegacyExternalStorage="true" ... >
    ...
  </application>