WebView relevant analytical method

WebView related operations

.
.
.

1. The four ways to load a web page

2. The control forward and back pages

3.Webview state management

4.webview commonly associated class Introduction

The operation control JS

6. Control the page size and scaling

7. caching policy

8.WebViewClient

9. The resource request a callback

10. Address interception

The error occurs when processing 11.WebViewClient

12.WebChromeClient processing web page information

13.android call JS code

14.JS call android Code

1. The four ways to load a web page:

1.1 loadUrl (String url)
The url can be a web URL:loadUrl(“https://www.csdn.net/”);

It can also be a html page in the local resource file:loadUrl("file:///android_asset/index.html");

Said the phone's SD card page:
loadUrl(webView.loadUrl("file://"+Environment.getExternalStorageDirectory().getPath()+"index.html")

1.2 loadUrl (String url, Map <
String, String> addidionalHttpHeaders) This parameter is to add a ddidionalHttpHeaders on the basis of the above-described method. This parameter will be added to RequestHeaders in.
Instructions;

    webView.setWebViewClient(new WebViewClient()
        {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            //这里放入了我们自定义的请求头
                Map<String,String > reqHeaders = new HashMap<>();
                reqHeaders.put("header_key","panghu");
                webView.loadUrl(url,reqHeaders);
                return super.shouldOverrideUrlLoading(view, request);
            }
        });

1.3 loadData (String data, String mimeType
, String encoding) This method allows us html code is loaded into a section of our in webview.
Instructions:

webView.loadData("<h1>HelloWord</>","text/html","utf-8");

1.4 loadData (String baseUrl, String data
, String minmeType, Sstring historyUrl) This method adds a baseUrl parameters and the HistoryURL code based on the upper side. This represents the path after the baseUrl and data spliced together. historyUrl represents the code hits the back when the jump.

2. Control page back and forward
all the back forward who rely on browsing history to determine the
key as follows:
2.1boolean CanGoBack (): Can Back
2.2 boolean canGoForward (): Can forward
2.3boolean canGoBackOrForward (int step ): can the specified number of steps forward or backward (forward is positive, negative for the reverse)
2.4 goBack void (): back to the previous
2.5 void goForward (): advance to the next
2.6 void goBackOrForward (int steps): forward or back to the page specified number of steps
2.7 void clearHistory (): empty history

3.Webview state management:
Similar Activity has a lifecycle, webview with similar state management:
onPause (): inform the kernel suspend all action on the current page
onResume (): inform the kernel to respond to all the action on the current page
onPauesTimers (): notification kernel suspend action on all pages
onResumeTimers (): inform the kernel recovery action all pages
destory (): destruction WebVIew

Activity of these callbacks with the callback function should be used together with

4.webview commonly associated class Description:
1.webSettings: webView to configure and manage
2.WebViewClient: page load callback handler notification
3.WebChromeClient :: assist webview to deal with the progress of JS dialog title

The control JS allowed to run:
the WebSettings webView.getSettings Settings = ();
settings.setJavaScriptEnabled (to true);

6. Zoom control pages:
setSupportZoom (boolean): whether to support the scaling
setBuiltInZoomControls (boolwan): Set the built-in zoom controls
setDisplayZoomControls (boolean): whether to display native zoom control

7. caching strategy:

wetSettings.setCacheMode (MODE_NAME);
MODE_NAME following ways
** LOAD_CACHE_ONLY: ** never use the cache
** LOAD_CACHE_ELSE_NETWORK: ** As long as there is a local cache on the use of local cache, the local cache is not loaded on a network resource
LOAD_DEFAULT (default) : according cache_control decide whether to use the cache
** LOAD_NO_CACHE: ** never use the cache, obtain only from the network

: 8.WebViewClient
various web callback notification process

        webView.setWebViewClient(new WebViewClient()
        {
            /**
             *在webview进行请求之前进行回调 
             * @param view
             * @param url
             * @return
             */
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }

            /**
             * 在webview进行请求之前进行回调 ,仅在5.0以后可以使用
             * @param view
             * @param request
             * @return
             */
            @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return super.shouldInterceptRequest(view, request);
            }

            /**
             * 在网页加载的 时候进行回调
             * @param view
             * @param url
             * @param favicon
             */
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            /**
             * 网页开始加载资源
             * @param view
             * @param url
             */
            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }

            /**
             * 网页加载完毕
             * @param view
             * @param url
             */
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });

10. Address interception
same callback method webclient, there is a method:
boolwan shouldOverrideUrlLoading (WebView View, String url): make callbacks to be loaded when the new url

 		  @Nullable
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return super.shouldInterceptRequest(view, url);
            }


		 /**
             * 
             * @param view
             * @param request
             * @return 返回false的时候代表webview进行处理新的请求,返回true的时候代表我们进行处理
             */
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
			if("http://www.baidu.com".equals(request.getUrl()))
				{
					view.loafUrl("http://www.mooc.com")
					return true;
				}
                return super.shouldOverrideUrlLoading(view, request);
            }

11.WebViewClient processing when an error occurs:


            /**
             * 在6.0以后使用
             * @param view
             * @param request
             * @param error
             */
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

12.WebChromeClient processing web page information:
Several important callback methods:

 webView.setWebChromeClient(new WebChromeClient()
        {
            /**
             * 获取网页加载的进度
             * @param view
             * @param newProgress
             */
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            /**
             * 获取网页的标题
             * @param view
             * @param title
             */
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }

            /**
             * 网页将要打开一个Alert的时候进行回调
             * @param view
             * @param url
             * @param message
             * @param result
             * @return 返回为false的时候表示webview对此弹出处理,返回true的时候代表我们进行处理  
             */
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

            /**
             * 在网页将要打开一个confirm对话框的时候进行回调
             * @param view
             * @param url
             * @param message
             * @param result
             * @return 返回为false的时候表示webview对此弹出处理,返回true的时候代表我们进行处理  
             */
            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }

            /**
             * 在网页将要打开一个Prompt对话框的时候进行回调
             * @param view
             * @param url
             * @param message
             * @param defaultValue
             * @param result
             * @return 返回为false的时候表示webview对此弹出处理,返回true的时候代表我们进行处理  
             */
            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
        });

In the latter three pop-up box, if we want to own processing logic, our results need to be returned to the JS code. We can use the result of this parameter result.confirm () or result.cancel (). Method to submit the results to the JS

13.android call the JS code:

webview.loadUrl("javaScript::${functionName}") //不需要返回值时调用
//需要返回值时调用 api>19
  webView.evaluateJavascript("javascript:${functionName}", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String s) {
                
            }
        });

14.JS call android Code:

When we visit over the intercept, we will get to jump to the domain name, and then intercept under the domain name. In fact, we can also use the domain name to convey certain information: We assume that the domain name "android:? // print msg = 123".
Then we arrived with our Android can be local print method according to the domain name. code show as below:

  @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Uri uri = Uri.parse(url);
                if("android".equals(uri.getScheme()))//协议名为android,表示为商定好的协议
                {
                    String funcName = uri.getAuthority();
                    if ("print".equals(funcName))
                    {
                        String msg = uri.getQueryParameter("msg");
                        print(msg);
                    }
                }
                return true;
            }

  private void print(String msg) {
        Log.d("panghu", "print: "+msg);
    }

This completes the JS code to call Android functions. When we need to return some data, we can use the method to call when the android JS, and the data as a parameter fixed JS method call.

Using object mapping mode (available after 4.2):
First, we have a mapping class:

public class DemoObject {

    @JavascriptInterface
    public String print(String msg)
    {
        Log.d(TAG, "print: "+msg);
        return "fanhuizhi";
    }
}

Then call:

webView.addJavascriptInterface(new DemoObject(),"android");

A name "android" as the object of this class. Html then, we have a JS function like this:

function getMsg()
{
	var result = android.print("hahaha") //这个result就是android代码给我们的返回值
}

WebView is about using these, there are deficiencies subsequent re perfect

Published 47 original articles · won praise 15 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41525021/article/details/104445882