WebView interactive architecture project practice (I) in-depth understanding of JVM

          android:layout_width="match_parent"

          android:layout_height="match_parent"/>



      ......



  </LinearLayout> 

``````

 // MainActivity.java

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        WebView webView = (WebView) findViewById(R.id.webview);

        webView.getSettings().setJavaScriptEnabled(true);

        webView.setWebViewClient(new WebViewClient() {



            @Override

            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                view.loadUrl(url);

                return true;

            }



            @TargetApi(21)

            @Override

            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

                view.loadUrl(request.getUrl().toString());

                return true;

            }

        });

        webView.loadUrl("https://ke.youdao.com");

    } 

```
  • If the accessed page contains Javascript code, you need to set WebView to support Javascript.

     webView.getSettings().setJavaScriptEnabled(true); 
    
    
  • If the page contains a connection, click the link. If you want to continue browsing the web page in the current browser, you need to rewrite the WebViewClient object of WebView.

    webView.setWebViewClient(new WebViewClient() {
    
    
    
        @Override
    
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
    
            view.loadUrl(url);
    
            return true;
    
        }
    
    
    
        @TargetApi(21)
    
        @Override
    
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
    
            view.loadUrl(request.getUrl().toString());
    
            return true;
    
        }
    
    }); 
    
    

    If you do not rewrite the WebViewClient object of WebView and click the connection in the page, a new link will be opened in the browser of the mobile phone system.

2. WebViewClient

In Section 1, we have simply used WebViewClient. There are other common methods that can be rewritten and used. Their meanings are as follows:

webView.setWebViewClient(new WebViewClient() {



    // Give the application the opportunity to handle some url requests. If it returns true, the request will be intercepted. If it returns false, it will not be intercepted and has been discarded

    @Override

    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        view.loadUrl(url);

        return true;

    }



    // Give the application the opportunity to handle some url requests. If it returns true, the request will be intercepted. If it returns false, it will not be intercepted. It is an alternative to the above method

    // WebResourceRequest contains the url, method and header of the request

    @TargetApi(21)

    @Override

    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

        view.loadUrl(request.getUrl().toString());

        return true;

    }



    // Callback when page starts loading

    @Override

    public void onPageStarted(WebView view, String url, Bitmap favicon) {

        super.onPageStarted(view, url, favicon);

    }



    // Callback at the end of page loading

    @Override

    public void onPageFinished(WebView view, String url) {

        super.onPageFinished(view, url);

    }



    // This method is called back when the resource corresponding to the url is loaded

    @Override

    public void onLoadResource(WebView view, String url) {

        super.onLoadResource(view, url);

    }



    // This method will be called back when loading the resource corresponding to the url. The difference is that the loaded data can be controlled by the return value. This method has been deprecated

    // If null is returned, WebView will load the resource normally

    // If an object of type WebResourceResponse is returned, WebView will use the object

    // Note that this method is not called in the UI thread

    @Override

    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

        return super.shouldInterceptRequest(view, url);

    }



    // It is an alternative to the above method, and the use method is consistent with the above method

    @Override

    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {

        return super.shouldInterceptRequest(view, request);

    }



    // Method that will be called back when there is an error loading resources

    @Override

    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {

        super.onReceivedError(view, request, error);

    }



    // An error occurred in the HTTP request while loading resources. This method will be called back

    @Override

    public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {

        super.onReceivedHttpError(view, request, errorResponse);

    }



    // This method is called back when there is an error requesting an HTTPS resource

    @Override

    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {

        super.onReceivedSslError(view, handler, error);

    }



    // Block key events in the browser

    // If true is returned, the key event is intercepted

    // If false is returned, WebView handles the event

    @Override

    public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {

        return super.shouldOverrideKeyEvent(view, event);

    }



    // This method is called back when the scaling of the page changes

    @Override

    public void onScaleChanged(WebView view, float oldScale, float newScale) {

        super.onScaleChanged(view, oldScale, newScale);

    }

}); 

3. WebChromeClient

Like WebViewClient, you can control some behaviors of WebView by setting the WebChromeClient object for WebView and overriding some of its methods.

webView.setWebChromeClient(new WebChromeClient() {



     // Page loading progress

     @Override

     public void onProgressChanged(WebView view, int newProgress) {

         L.i("onProgressChanged " + newProgress);

         super.onProgressChanged(view, newProgress);

     }



     // Received the title of the web page

     @Override

     public void onReceivedTitle(WebView view, String title) {

         L.i("onReceivedTitle " + title);

         super.onReceivedTitle(view, title);

     }



     // Received icon of web page

     @Override

     public void onReceivedIcon(WebView view, Bitmap icon) {

         super.onReceivedIcon(view, icon);

     }



     @Override

     public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {

         super.onReceivedTouchIconUrl(view, url, precomposed);

     }



     // This method will be called when you click the full screen button of the played flash video on the H5 page

     @Override

     public void onShowCustomView(View view, CustomViewCallback callback) {

         super.onShowCustomView(view, callback);

     }



     // The method that will be called when canceling full screen corresponding to onShowCustomView()

     @Override

     public void onHideCustomView() {

         super.onHideCustomView();

     }



     @Override

     public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {

         super.onShowCustomView(view, requestedOrientation, callback);

     }



     // http://www.cnblogs.com/ufreedom/p/4229590.html

     // This method is called when a new Window is created

     @Override

     public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {

         return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);

     }



     // Corresponding to the onCreateWindow() method, close the Window

     @Override

     public void onCloseWindow(WebView window) {

         super.onCloseWindow(window);

     }



     // This method is called when WebView gets focus

     @Override

     public void onRequestFocus(WebView view) {

         super.onRequestFocus(view);

     }



     // This method is called when an Alert window pops up in Js code

     @Override

     public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

         return super.onJsAlert(view, url, message, result);

     }



     // This method is called when the Confirm window pops up in the Js code

     @Override

     public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {

         return super.onJsConfirm(view, url, message, result);

     }



     // This method is called when the Prompt window pops up in Js code

     @Override

     public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {

         return super.onJsPrompt(view, url, message, defaultValue, result);

     }



     // This method is called before Js loads

     @Override

     public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {

         return super.onJsBeforeUnload(view, url, message, result);

     }



     // Print the log console information in Js and discard it

     @Override

     public void onConsoleMessage(String message, int lineNumber, String sourceID) {

         super.onConsoleMessage(message, lineNumber, sourceID);

     }



     // Print the log console information in Js and discard it

     @Override

     public boolean onConsoleMessage(ConsoleMessage consoleMessage) {

         return super.onConsoleMessage(consoleMessage);

     }

 }); 

4. Difference between webviewclient and WebChromeClient

WebViewClient mainly helps WebView handle some network request behaviors and operations, such as requests for various resources, notification of errors in requesting resources, HTTPS request errors, etc.

WebChromeClient mainly helps WebView handle some Javascript related details, such as the pop-up of various dialog boxes, the printing of log information in Js, the creation and closing of Window, and the reception of title and icon.

5. Interaction between JS and Java code

It is a common saying that Java code and Js code call each other. Now there are some excellent open source frameworks that are very convenient to use, but their principles are the same. Here is how Js code and Java code interact.

5.1 Js code calling Java code

private class InnerClass {



    private Context mContext = null;



    public InnerClass(Context context) {

        mContext = context;

    }



    @JavascriptInterface

    public void toastMessage(String msg) {

        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();

    }

} 

public class JSBridgeActivity extends AppCompatActivity {

private WebView webView = null;



@Override

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_jsbridge);

    initWebView();

}



private void initWebView() {

    webView = (WebView) findViewById(R.id.webView);

    webView.getSettings().setJavaScriptEnabled(true);

    webView.addJavascriptInterface(new InnerClass(JSBridgeActivity.this), "innerClass");

    webView.loadUrl("file:///android_asset/demo.html");

    webView.setWebChromeClient(new WebChromeClient());

}

}



*   Famous for `InnerClass` Class in which the method `toastMessage(String msg)` cover `@JavascriptInterface` Modified by annotation

*   set up WebView Object support JavaScript,And call `addJavascriptInterface(Object object, String name)` Method, will `InnerClass` Object passed in WebView Object

*   stay WebView To load a page Js Code, you can `name` call `InnerClass` Object `toastMessage(String msg)` Method, as follows:



function testPrompt(){

  window.innerClass.toastMessage("jsbridge");

}



### [] (5.2 Java code calls Js code



If there are the following Js Method, as follows:



function testConfirm(){

var temp = "temp";

confirm(temp);

}

end of document

Well, that's all for today's sharing. If you don't know how to prepare for the interview, break through the status quo and improve yourself, and don't know enough about your future, you can see how your peers break through the status quo and learn, To absorb their interview and work experience and improve their interview plan and career planning.

Here is a set of advanced learning videos and interview information packages collected and summarized from some of the interviews I have participated in since my work. I mainly hope that the interview can be smoother in today's bad environment, and I hope it can help you~
CodeChina open source project: Android learning notes summary + mobile architecture Video + big factory interview real questions + project actual combat source code

As shown in:

function testPrompt(){

      window.innerClass.toastMessage("jsbridge");

} 

5.2 Java code calling Js code

If there is the following Js method, it is as follows:

function testConfirm(){

    var temp = "temp";

    confirm(temp);

} 
## end of document

Well, that's all for today's sharing. If you don't know how to prepare for the interview, break through the status quo and improve yourself, and don't know enough about your future, you can see how your peers break through the status quo and learn, To absorb their interview and work experience and improve their interview plan and career planning.

> Here is a collection of some interviews I have participated in since my work**Advanced learning video and interview feature package**,I hope the interview can go smoothly in today's bad environment. I hope it can help you~
> **[CodeChina Open source projects:< Android Summary of study notes+Mobile architecture video+Real interview questions for large factories+Project practice source code](https://codechina.csdn.net/m0_60958482/android_p7)**

[External chain picture transfer...(img-5UfQonn8-1630587651270)]

Keywords: Javascript Android Design Pattern webview

Added by pyfsapple on Fri, 03 Sep 2021 02:59:55 +0300