WebView uses common overlooked points

1.WebView uses
1.webview: responsible for page rendering
2.WebViewClient: assists WebView to handle various notifications and request events
3.WebChromeClient: assists WebView to handle dialog boxes in JavaScript, URL icons and titles, progress bars, etc.
Details:
If we To control the jumping methods of different links, we need to inherit WebViewClient and rewrite the shouldOverrideUrlLoading() method

Two notes on the shouldOverrideUrlLoading() method:

1 method return value

Return true: The Android system will process the URL, usually to invoke the system browser.
Returns false: the current WebView handles the URL.

Since it is set back to false by default, if we only want to handle link jumps in WebView, we only need to set mWebView.setWebViewClient(new WebViewClient())

注意:
如果你只需要避免启动系统浏览器来加载页面的情况,只需要这么写就可以了

webView.setWebViewClient(new WebViewClient());

url存在重定向,无法回退

shouldOverrideUrlLoading(WebView view, String url)

的返回值决定了webview是否自动处理该url,也就是是否加载。当返回true时,由程序处理,当返回false时,webview会自己处理,也就是相当于自动执行了loadUrl方法。

2 method deprecated problem

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        view.loadUrl(request.toString());
        return true;
    }

The shouldOverrideUrlLoading() method is marked deprecated when API >= 24, its alternative is

3. Page fallback

Android's return key, if you want to return the web page in WebView, you can override the onKeyEvent() method.

4 Page sliding
Three methods of judging the height:

1.getScrollY():该方法返回的是当前可见区域的顶端距整个页面顶端的距离,也就是当前内容滚动的距离.
2.getHeight();
getBottom();
该方法都返回当前WebView这个容器的高度

3.getContentHeight();:
返回的是整个html的高度, 但并不等同于当前整个页面的高度, 因为WebView有缩放功能, 所以当前整个页面的高度实际上应该是原始html的高度:

if (webView.getContentHeight() * webView.getScale() == (webView.getHeight() + webView.getScrollY())) {
    //已经处于底端
}

if(webView.getScrollY() == 0){
    //处于顶端
}

 不过从API 17开始, mWebView.getScale()被标记为deprecated
public class CustomWebView extends WebView {

public CustomWebView(Context context) {
    super(context);
    setWebViewClient(new WebViewClient() {
        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            super.onScaleChanged(view, oldScale, newScale);
            mCurrentScale = newScale
        }
    });
}


2. WebView cache implementation

When the html page is loaded, two folders, database and cache, will be generated under the /data/data/package name directory.

The requested url record is saved in WebViewCache.db
and the content of the url is saved in the WebViewCache folder

控制缓存行为的相关API:
WebSettings webSettings = mWebView.getSettings();
//优先使用缓存
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); 
//只在缓存中读取
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ONLY);
/不使用缓存
WwebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

clear cache

clearCache(true); //清除网页访问留下的缓存,由于内核缓存是全局的因此这个方法不仅仅针对webview而是针对整个应用程序.
clearHistory (); //清除当前webview访问的历史记录,只会webview访问历史记录里的所有记录除了当前访问记录.
clearFormData () //这个api仅仅清除自动完成填充的表单数据,并不会清除WebView存储到本地的数据。

3. WebView local resource access
When we load the content taken from the web server in WebView, we cannot access local resources, such as image resources in the assets directory, because such behavior is a cross-domain behavior (Cross-Domain ), while WebView is prohibited
. The solution to this problem is to download the html content to the local first, and then use loadDataWithBaseURL to load the html. In this way, the link of file:///android_asset/xxx.png can be used in html to refer to
the resources under assets in the package.

private void loadWithAccessLocal(final String htmlUrl) {
    new Thread(new Runnable() {
        public void run() {
            try {
                final String htmlStr = NetService.fetchHtml(htmlUrl);
                if (htmlStr != null) {
                    TaskExecutor.runTaskOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            loadDataWithBaseURL(htmlUrl, htmlStr, "text/html", "UTF-8", "");
                        }
                    });
                    return;
                }
            } catch (Exception e) {
                Log.e("Exception:" + e.getMessage());
            }

            TaskExecutor.runTaskOnUiThread(new Runnable() {
                @Override
                public void run() {
                    onPageLoadedError(-1, "fetch html failed");
                }
            });
        }
    }).start();
}

4. The difference between WebView loadUrl and reload

loadUrl will have a cache policy, and will not refresh when encountering a webpage with #, and reload will force a refresh regardless of the cache policy.
However, the previous two did not take effect after experimenting in the project. Change to: webview.loadUrl(“javascript:window.location.reload(true)”); take effect. The specific principle is to be studied
5.WebView clearHistory() does not take effect

The reason for this situation is that when we loadUrl, because the new page has not been fully loaded, clearHistory does not work, because at least one page must be at the top, so the previous page has not been removed. To solve this problem, you can add the clearHistory method in the onPageFinished method, or call the clearHistory method with a delay.

Guess you like

Origin blog.csdn.net/github_37610197/article/details/128727521