首页 > 解决方案 > android中的webview主机应用程序

问题描述

我是初学者。当我开始使用 webview 制作应用程序时。

我在文档上看到https://developer.android.com/reference/android/webkit/WebViewClient#shouldOverrideUrlLoading(android.webkit.WebView,%20java.lang.String)

当即将在当前 WebView 中加载 URL 时,让宿主应用程序有机会进行控制。

我英语很弱,但我知道什么是托管。但我不明白什么是主机应用程序,为什么它会这样调用?

1)主机应用程序是指我的应用程序中的网络浏览器或网络视图吗?

2) shouldoverrideurlloading 如何与 webview 和浏览器一起使用应该会有所帮助。

3) return true 会打开一个网络浏览器??

标签: androidwebview

解决方案


@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    final Uri uri = Uri.parse(url);
    return handleUri(view, uri);
}

@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
    final Uri uri = request.getUrl();
    return handleUri(view, uri);
}

和 handleUri 方法

private boolean handleUri(WebView view, Uri uri) {
    final String scheme = uri.getScheme();
    final String host = uri.getHost();
    // 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 (scheme.startsWith("http:") || scheme.startsWith("https:")) {
        view.loadUrl(uri.getPath());
        return true;
    } else {
        return false;
    }
}

推荐阅读