admin管理员组

文章数量:1387360

Opening PDFs coming from another web link. PDFs are supposed to be downloaded from the link and then an external app is used to open to PDF. This applies for all the resources.

.xlsx .pdf .jpeg

Opening PDFs coming from another web link. PDFs are supposed to be downloaded from the link and then an external app is used to open to PDF. This applies for all the resources.

.xlsx .pdf .jpeg

Share Improve this question asked Mar 17 at 9:44 AnglesvarAnglesvar 1,1549 silver badges18 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

For this, we need to understand what Android does behind the picture. When we open a web view through WebViewClient it considers everything as an unrelated resource. If we want to open a PDF from the web view itself, we can override onLoadResource.

class CustomWebViewClient: WebViewClient()
{
    override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean
    {
        if (request == null)
        {
            return false
        }

        view!!.settings.allowFileAccess = true
        view.settings.allowContentAccess = true
        view.settings.domStorageEnabled = true
        view.settings.javaScriptEnabled = true
        view.settings.loadWithOverviewMode = true

        view.loadUrl(request.url.toString())

        return false
    }

    override fun onLoadResource(view: WebView?, url: String?) {
        super.onLoadResource(view, url)
        if (url!!.contains(".pdf")) {
            WebHelper.openBrowser(url.toUri())
        }
    }

    override fun onReceivedError(
        view: WebView?,
        request: WebResourceRequest?,
        error: WebResourceError?
    ) {
        super.onReceivedError(view, request, error)
        Log.e("error", error.toString())
    }
}

本文标签: kotlinHow to load resources coming from the webview in androidStack Overflow