无法使用 WebView 打开 PDF 文件

Can not open PDF file using WebView

我试图在网络视图中使用 url 显示 pdf 文件。尽管 webview 正在加载像 google.com 这样的网页,但当我尝试加载 pdf 的 url 时,它不会加载任何内容或抛出任何异常。

url 在 google chrome 桌面浏览器中加载 pdf,所以我想问题不在于 url 本身。

这是我目前编写的代码:

onCreateView() 加载 pdf 的 Fragment

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_brochure, container, false);
        webView = view.findViewById(R.id.webView);
//        webView.loadUrl("https://google.com");
        webView.loadUrl("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf");
//        webView.loadUrl(brochureUrl);
        // Enable Javascript
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);

        // Force links and redirects to open in the WebView instead of in a browser
        webView.setWebViewClient(new WebViewClient());
        return view;
    }

布局(xml 文件):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/purple_500"
    tools:context=".ui.project_details.project_details_pages.BrochureFragment">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"/>

</LinearLayout>

清单文件(只有我认为相关的部分)

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        ...
        ...
        ...
        android:supportsRtl="true"
        android:usesCleartextTraffic="true">

我想知道我错过了什么。另外,如果我能学习如何调试此类问题,那就太好了。

使用 webView 加载 pdf 时出现一些问题。您可以使用以下代码来解决您的问题。此方法借助驱动器查看 pdf webView.Finally 让我知道您的问题是否已解决

webview.getSettings().setJavaScriptEnabled(true); 
    String pdf = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
    webview.loadUrl("https://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);