为将来的读者详细记录:
简短的答案是您需要覆盖这两种方法。该shouldOverrideUrlLoading(WebView view, String url)
方法已在API 24中弃用,并且已在API 24 shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
中添加了该方法。如果您要定位的是旧版android,则需要前一种方法,并且如果要定位到android 24(或更高版本,如果有人在不久的将来会阅读此方法)建议也覆盖后一种方法。
以下是有关如何完成此操作的框架:
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.
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;
}
}
}
就像一样shouldOverrideUrlLoading
,您可以想出一种类似的shouldInterceptRequest
方法。