Android - 获取在webview中点击的链接用户

时间:2012-05-09 22:44:45

标签: java android 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/");
}

1 个答案:

答案 0 :(得分:4)

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

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

请参阅webview shouldinterceptrequest example