【问题标题】:Android - Get link user clicked on in webviewAndroid - 获取用户在 webview 中点击的链接
【发布时间】:2012-05-09 22:44:44
【问题描述】:

如何获取用户在 webview 中点击的链接?示例:我的 webview 将用户带到列出信息和 PDF 的网站,如果用户单击 PDF,我想获取用户单击的 PDF 文件的链接并将其放入 Google 的在线查看器中。我的代码不起作用,因为它不会拦截点击链接。有什么想法吗?

这是我所拥有的:

webview.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // do your handling codes here, which url is the requested url
            // probably you need to open that url rather than redirect:
            if (url.startsWith("tel:")) {
                startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            } else if (url.startsWith("mailto:")) {
                url = url.replaceFirst("mailto:", "");
                url = url.trim();
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL,
                        new String[] { url });
                startActivity(i);

            } else if (url.startsWith("geo:")) {
                try {
                } catch (Exception e) {
                    System.out.println(e);
                }

            } else if (url.endsWith("pdf")) {
                try{
                    String pdf = (url);
                    webview.loadUrl("http://docs.google.com/viewer?url=" + pdf);
                    }
                    catch (ActivityNotFoundException e)
                    {
                     Toast.makeText(atcFaa.this, "No PDF Viewer Installed", Toast.LENGTH_LONG).show();
                    }

            }

            else {
                view.loadUrl(url);
            }
            return true;
            // then it is not handled by default action
        }
    });
webview.loadUrl("http://www.somewebsite.com/publications/");
}

【问题讨论】:

    标签: java android webview


    【解决方案1】:

    我认为您要覆盖的方法是WebViewClient.shouldInterceptRequest(WebView view, String url)

    public WebResourceResponse shouldInterceptRequest (WebView view, String url)
    
    • 将资源请求通知主机应用程序并允许 应用程序返回数据。如果返回值为 null,则 WebView 会像往常一样继续加载资源。否则,该 返回响应和数据将被使用。注意:此方法由 网络线程,因此客户端在访问时应小心 私人数据。参数

    webview shouldinterceptrequest example

    【讨论】:

    • 我看到最低 SDK 版本是 11,如该示例中所述。我正在为版本 10 构建(适用于仍在使用 2.3.3 Gingerbread 的人)。升级到下一个版本 11 是我唯一的选择吗?
    猜你喜欢
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 2017-12-21
    相关资源
    最近更新 更多