2017-01-01 95 views
0

我在加载特定url的应用中有WebView,但有可能在使用该应用时,用户可能会在Web视图内被转到另一个url,例如www。 cheese.com,不应该在应用程序内查看。 是否有可能在WebView范围内侦听该网址(www.cheese.com),并在加载完成之前是否开始加载重定向到另一个网址?在Webview中重定向特定URL - Android

public class MainActivity extends AppCompatActivity { 

    private WebView mWebView; 

     mWebView.loadUrl("https://example.com"); 

     // Enable Javascript 
     WebSettings webSettings = mWebView.getSettings(); 
     webSettings.setJavaScriptEnabled(true); 

    } 
} 
+0

你们是不是说,如果URL开始(www.cheese.com),那么它会重定向到另一个网址? –

+0

是的,绝对 – user1419810

+0

然后你必须使用'shouldOverrideUrlLoading(WebView视图,String url)'方法在这个方法中可以做到这一点。 –

回答

0

尝试使用这样的:

webView.setWebViewClient(new WebViewClient() { 
     public boolean shouldOverrideUrlLoading(WebView view, String url) { 

      if (url != null && url.startsWith("http://www.cheese.com")) { 
       //do what you want here 
       return true; 
      } else { 
       return false; 
      } 
     } 
    }); 
1
// Load CustomWebviewClient in webview and override shouldOverrideUrlLoading method 
    mWebView.setWebViewClient(CustomWebViewClient) 



class CustomWebViewClient extends WebViewClient { 

    @SuppressWarnings("deprecation") 
    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, String url) { 
     final Uri uri = Uri.parse(url); 
     return handleUri(uri); 
    } 

    @TargetApi(Build.VERSION_CODES.N) 
    @Override 
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { 
     final Uri uri = request.getUrl(); 
     return handleUri(uri); 
    } 

    private boolean handleUri(final Uri uri) { 
     Log.i(TAG, "Uri =" + uri); 
     final String host = uri.getHost(); 
     final String scheme = uri.getScheme(); 
     // Based on some condition you need to determine if you are going to load the url 
     // in your web view itself or in a browser. 
     // You can use `host` or `scheme` or any part of the `uri` to decide. 

     /* here you can check for that condition for www.cheese.com */ 
     if (/* any condition */) { 
      // Returning false means that you are going to load this url in the webView itself 
      return false; 
     } else { 
      // Returning true means that you need to handle what to do with the url 
      // e.g. open web page in a Browser 
      final Intent intent = new Intent(Intent.ACTION_VIEW, uri); 
      startActivity(intent); 
      return true; 
     } 
    } 
}