“shouldOverrideUrlLoading”真的被弃用了吗?如果是这样,我可以用什么代替?
似乎 shouldOverrideUrlLoading
已被弃用我使用了 Android N 中的一些新功能(例如 Data Saver),因此定位 Marshmallow 对解决问题没有帮助,因为我需要使用这些新功能,这是我使用的部分代码:
public boolean shouldOverrideUrlLoading(WebView webview, String url) {
if (url.startsWith("http:") || url.startsWith("https:")) {
...
} else if (url.startsWith("sms:")) {
...
}
...
}
这是 Android Studio 给我的信息:
Overrides deprecated method in 'android.webkit.WebViewClient' This inspection reports where deprecated code is used in the specified inspection scope.
Google says nothing about that deprecation .
我想知道使用 @SuppressWarnings("deprecation")
是否可以让我在自 API 19 到最新的 Android N Beta(及其发布时的最终版本)之前的所有设备上工作,我自己无法测试,我从未使用过它,我需要确保它有效,所以,任何人都可以告诉?
最佳答案
为 future 的读者详细记录:
简短的回答是您需要覆盖这两种方法。 shouldOverrideUrlLoading(WebView view, String url)
方法在 API 24 中已弃用,shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
方法在 API 24 中添加。如果您的目标是较早版本的 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
方法提出类似的方法。
关于android - `shouldOverrideUrlLoading` 真的被弃用了吗?我可以用什么代替?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36484074/