如何在webview中打开链接或根据域名默认打开浏览器?

ace*_*ace 5 android

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

我试图使用公共布尔值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) {

                   }
               }
}
Run Code Online (Sandbox Code Playgroud)

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

Dev*_*red 22

创建并附WebViewClient加到您的后WebView,您已覆盖默认行为,其中Android将允许ActivityManager将URL传递给浏览器(这仅在视图上未设置客户端时发生),请参阅有关方法的文档以获取更多信息.

一旦你附加了一个WebViewClient,返回的假表单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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道这似乎有点违反直觉,因为你希望return false;完全绕过它WebView,但是一旦你使用自定义就不是这种情况WebViewClient.

希望有所帮助!

  • 谢谢Wireless Designs,这很有效.请注意,代码中的"request"应该是Uri.parse(url). (2认同)

Com*_*are 5

如果你不能解释什么"不能正常工作"的意思,我们不能打扰给你很多具体的帮助.

使用shouldOverrideUrlLoading().检查提供的URL.如果它是一个你想保留的WebView,调用loadUrl()WebViewURL和回报true.否则,返回false并让Android正常处理它.