Android webview打开特定域的站点
我正在尝试制作一个应用程序,在webview中打开某个网站的所有网页,例如www.yahoo.com,但在defaultbrowser中打开所有其他网页。这是我正在使用的代码,但不能完全让它工作Android webview打开特定域的站点,android,webview,Android,Webview,我正在尝试制作一个应用程序,在webview中打开某个网站的所有网页,例如www.yahoo.com,但在defaultbrowser中打开所有其他网页。这是我正在使用的代码,但不能完全让它工作 private class MyWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("http://www.yahoo.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;
}
}
在我看来,这段代码应该可以工作,但当我加载yahoo时,它仍然会转到外部浏览器。任何帮助都将不胜感激。谢谢 getHost()
通常只返回域名,有时还加上www.
前缀。它从不包含http://
协议AFAIK。尝试使用:
if ((Uri.parse(url).getHost().equals("yahoo.com")) || (Uri.parse(url).getHost().equals("www.yahoo.com")) || (Uri.parse(url).getHost().equals("m.yahoo.com"))) {
//Your code
这里有一种不同的方法
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String urlHost = Uri.parse(url).getHost();
switch (urlHost) {
case "yahoo.com":
return false;
case "www.yahoo.com":
return false;
case "m.yahoo.com":
return false;
default:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
试试这个,它会对你有帮助的
private WebView mWebview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yahoo);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}
});
mWebview .loadUrl("http://www.yahoo.com");
setContentView(mWebview );
}
}
不幸的是,这段代码并没有解决这个问题。当在浏览器中而不是在webview中打开yahoo.com时,url为m.yahoo.com。也许这与此有关?