2017-01-01 129 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; 
     } 
    } 
}