2011-02-05 45 views
5

我有WebView,我想在webview中打开属于域www.example.org的链接,而在我的应用程序之外的默认浏览器打开所有其他链接(如果点击)。如何在web视图中打开链接或根据域名默认打开浏览器?

我试图使用公共布尔值shouldOverrideUrlLoading(WebView视图,字符串url),但它不能正常工作。

这里是不起作用的代码:

public class MyWebViewClient extends WebViewClient { 
    @Override 
       public boolean shouldOverrideUrlLoading(WebView view, String url) { 
        try { 
        URL urlObj = new URL(url); 
        if (urlObj.getHost().equals("192.168.1.34")) { 
         view.loadUrl(url); 
         return true; 
        } else { 
         view.loadUrl(url); 
         return false; 
        } 
        } catch (Exception e) { 

        } 
       } 
} 

在这两种情况下(返回true,并返回false)的URL是由我的应用程序处理。

+1

这个代码真的让你不知道什么不同的行为返回不同的布尔值时,因为你是在这两种情况下调用view.loadUrl(),由此产生的相同的结果。如果你从两个语句中删除了这行,你会发现返回false仍然会在WebView中加载url ...并且返回true什么也不做(你必须手动执行某些操作)。 – Devunwired 2011-02-07 14:32:12

回答

22

一旦你创建并附加WebViewClientWebView,你已经覆盖默认行为,其中Android将允许ActivityManager到URL传递给浏览器(这只有在没有客户端被设置在视图上出现),见the docs on the method for more

一旦你连接一个WebViewClient,返回false形式shouldOverrideUrlLoading()传递的URL WebView,而返回true告诉WebView什么也不做......因为你的申请将照顾它。不幸的是,这些路径都不会让Android将URL传递给浏览器。像这样的东西应该解决您的问题:

@Override 
public boolean shouldOverrideUrlLoading(WebView view, String url) { 
    try { 
     URL urlObj = new URL(url); 
     if(TextUtils.equals(urlObj.getHost(),"192.168.1.34")) { 
     //Allow the WebView in your application to do its thing 
     return false; 
     } else { 
     //Pass it to the system, doesn't match your domain 
     Intent intent = new Intent(Intent.ACTION_VIEW); 
     intent.setData(Uri.parse(url)); 
     startActivity(intent); 
     //Tell the WebView you took care of it. 
     return true; 
     } 
    } 
    catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

我知道这似乎有点违反直觉,你会期望return false;完全规避WebView,但这不是一旦你使用自定义WebViewClient的情况。

希望有帮助!

+0

感谢代码,但不幸的是这也不起作用。我尝试了你的代码,一旦我启动应用程序,外部浏览器就会加载url(www.example.org)。 – ace 2011-02-05 18:44:07

5

如果你不能解释什么“不能正常工作”的意思,我们不能打扰你给你很多具体的帮助。使用shouldOverrideUrlLoading()。检查提供的URL。如果这是您想要保留在WebView中的一个,请在WebView上用URL调用loadUrl(),并返回true。否则,返回false并让Android正常处理它。

1

以下添加到您的活动

@Override 
      public boolean shouldOverrideUrlLoading(WebView view, String url) { 
       if(Uri.parse(url).getHost().endsWith("192.168.1.34")) { 
        view.loadUrl(url); 
        Log.d("URL => ", url); // load URL in webview 
        return false; 
       } 

       Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); 
       view.getContext().startActivity(intent); // Pass it to the system, doesn't match your domain 
       return true; 
      } 
相关问题