如何在WebView Android中过滤手机和其他Web链接

问题描述 投票:0回答:3

我想要的是在网页视图中保留链接,只要它们是网站的一部分,但外部链接应该启动到外部网络浏览器。另外在网站上我有电话链接的电话:555-323-2323,如果我使用电话号码下面的代码工作并启动手机应用程序但外部链接无法正常工作。

@Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        if (url.contains("tel:")) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return true;
        } 
        if (Uri.parse(url).getHost().equals("www.example.com")) {
            // This is my web site, so do not override; let my WebView load the page
            return false;
        }
        // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
        return true;
android webview external
3个回答
0
投票

事情不起作用的主要原因是因为你有一个if-else而且两个分支都返回true。 else语句之后的所有代码都无法访问。删除else语句或更改该逻辑。


0
投票
  • 删除第一个语句(view.loadUrl(url))。
  • 删除else第一个条件的一部分。

您的代码看起来像这样:

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.contains("tel:")) {
        startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
        return true;
    } 
    if (Uri.parse(url).getHost().equals("www.example.com"))
        // This is my web site, so do not override; let my WebView load the page
        return false;

    // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs  
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent);
    return true;
} 

0
投票

我使用这个解决方案:

 @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.contains("tel:")) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        }
        if (Uri.parse(url).getHost().equals(URL)) {
            // This is my web site, so do not override; let my WebView load the page
            return super.shouldOverrideUrlLoading(view, url);
        }
        return super.shouldOverrideUrlLoading(view, url);
    }
© www.soinside.com 2019 - 2024. All rights reserved.