Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?
是否真的应该弃用" shouldOverrideUrlLoading"? 如果是这样,我该怎么用呢?
似乎不推荐使用
1 2 3 4 5 6 7 8 | 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对这种弃用一言不发。
我想知道使用
为将来的读者详细记录:
简短的答案是您需要覆盖这两种方法。在API 24中弃用了
以下是有关如何完成此操作的框架:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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; } } } |
就像
The version I'm using I think is the good one, since is the exact same as the Android Developer Docs, except for the name of the string, they used"view" and I used"webview", for the rest is the same
不它不是。
N Developer Preview的新功能具有以下方法签名:
1 | public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) |
所有Android版本(包括N)都支持的方法具有以下方法签名:
1 | public boolean shouldOverrideUrlLoading(WebView view, String url) |
So why should I do to make it work on all versions?
覆盖已弃用的参数,该参数以
用
1 2 3 | public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return shouldOverrideUrlLoading(view, request.getUrl().toString()); } |
实施不推荐使用和不推荐使用的方法,如下所示。第一个是处理API级别21和更高级别,第二个是处理低于API级别21
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | webViewClient = object : WebViewClient() { . . @RequiresApi(Build.VERSION_CODES.LOLLIPOP) override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean { parseUri(request?.url) return true } @SuppressWarnings("deprecation") override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean { parseUri(Uri.parse(url)) return true } } |