Use WebView in Android

Keywords: Javascript Android network Windows

Role: Controls that display html rich text
 --Load html:
LoadData (String html,'text/html; charset=utf-8', null) loads HTML web page content
 loadUrl(String url) loads web page data from the Internet
 LoadUrl (String url, HashMap < String, String > headers) loads the web page with a request header parameter
 loadUrl(String url) loads web page data from the Internet



- Basic Settings
 webView.getSettings().setJavaScriptEnabled(true); //Support for running javascript

webView.setWebChromeClient(new WebChromeClient()); //Support running special javascript (for example, alert())

WebView.setWebViewClient (new WebViewClient ();//When clicking on a hyperlink address, the browser will not be opened for access, but will always browse the page in this app

[Note:]
In addition to loading server-side Web pages, WebView can also load Web page files from the local asset directory.The format of the web page file is "file:///android_asset/file name".

What WebSettings do: With the code above, WebView can load web content, but Javascript code for HTML text cannot load and run.The WebSettings class is used to solve this problem.In addition to setting whether Javascript is supported or not, the WebSettings class has a set family of methods to set the properties and state of the WebView.The WebSettings object is obtained by the WebView object's getSettings() method.
How to get WebSettings: via the getSetting() method of the WebView object

----WebSettings Basic usage:
setJavaScriptEnabled(boolean flag);  //Set whether js is supported

setBlockNetworkImage(boolean flag)  //Set whether to prevent network pictures from loading

setDefaultFontSize(int size)   //Set default font size

setFixedFontFamily(String font)  //Set Fixed Font

setDefaultTextEncodingName(String encoding)  //Set the default character set for decoding

setAllowFileAccess(boolean allow)   //Sets whether access to files in the WebView is allowed.This is the asset and resource file under the file:///android_asset and file:///android_res paths.Access is allowed by default.

setLayoutAlgorithm(LayoutAlgorithm) //Set layout algorithm

setPluginsEnabled(true);  //Support Plugins 

setUseWideViewPort(false);  //Resize pictures to fit webview 

setSupportZoom(boolean support)  //Set whether zooming is supported

setBuiltInZoomControls(boolean enabled)  //Loading HTML text content into WebView

setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); //Supports content re-layout  

supportMultipleWindows();  //Multiple windows 

setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  //Turn off caching in webview 

setAllowFileAccess(true);  //Set Accessible Files 

setNeedInitialFocus(true); //Set node for webview when webview calls requestFocus

setJavaScriptCanOpenWindowsAutomatically(true); //Support opening new windows via JS 

setLoadWithOverviewMode(true); // Zoom to screen size

setLoadsImagesAutomatically(true);  //Supports automatic loading of pictures

- WebViewClient role: WebView solves the issue of Javascript support.But a new problem has arisen.When you click on a hyperlink in the WebView, you want the target page to appear in the current WebView, but you open the system browser to load the target page.To solve this problem, use the WebViewClient class.The WebViewClient class is designed to assist WebView in handling events such as notifications, requests, and so on.Calling the setWebViewClient() method through the WebView object specifies a WebViewClient object, overrides the shouldOverrideUrlLoading() method in the WebViewClient object so that when a new connection exists, the current WebView is used to display the Web page.In addition to WebViewClient, there are other methods
- Specific use of WebViewClient:

doUpdateVisitedHistory(WebView view, String url, boolean isReload)  //(Update History) 

onFormResubmission(WebView view, Message dontResend, Message resend) //(Application re-requests web page data) 

onLoadResource(WebView view, String url) // Called when page resources are loaded, and each resource (such as a picture) is loaded once. 

onPageStarted(WebView view, String url, Bitmap favicon) //This event is called to start loading a page, where we can usually set up a loading page to tell the user that the program is waiting for a network response. 

onPageFinished(WebView view, String url) //Called at the end of page loading.Similarly, we know a page is loaded, so we can close the loading bar and switch program actions. 

onReceivedError(WebView view, int errorCode, String description, String failingUrl)// (Report error information) 

onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,String realm)//(Authorization request for return information) 

onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) //Rewriting this method allows the webview to process https requests.

onScaleChanged(WebView view, float oldScale, float newScale) // (Called when the WebView changes) 

onUnhandledKeyEvent(WebView view, KeyEvent event) //(Called when the Key event is not loaded) 

shouldOverrideKeyEvent(WebView view, KeyEvent event)//Rewrite this method to handle key events in the browser. 

shouldOverrideUrlLoading(WebView view, String url) 
//When clicking on the requested link is invoked, rewriting this method to return true indicates whether clicking on a link in a web page or jumping in the current webview does not jump to the browser side.This function allows us to do a lot of things, such as read some special URL s, so we can not open the address, cancel this operation, and do other pre-defined operations, which is very necessary for a program.
-------android End and JavaScript Interaction:
android call JS Method
    webView.loadUrl("javascript:Method Name()");

JS call android Method
1,android End creates a class (for example MyJS),And declares a let in this class js The method invoked (for example click)

2,Declare an annotation on this method@JavascriptInterface

3,call webview.addJavascriptInterface(new MyJS(this), "app");Method.

4,stay JS End Pass app.click();call android End method

The webview is just like any other control and can display html directly when applied to it

The development code is as follows:

webView = (WebView) findViewById(R.id.webview);
//        webView.loadData(htmlstr, "text/html;charset=utf-8", null);


WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);//Let WebView support javascript
settings.setDefaultTextEncodingName("utf-8");//Set Character Set
//        settings.setBlockNetworkImage(true); //Settings cannot access network pictures
//        settings.setSupportZoom(true);//Turn on scaling of web pages
//        settings.setBuiltInZoomControls(true);

//        settings.setLoadWithOverviewMode(true);//Set page zoom to screen size
//        settings.setUseWideViewPort(true);

webView.setWebViewClient(new WebViewClient(){

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d("print", "Request Connected URL: " + url);
                return super.shouldOverrideUrlLoading(view, url);
}

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
                Log.d("print", "Start loading connections:" + url);
}

@Override
public void onPageFinished(WebView view, String url) {
                Log.d("print", "Page load finished:" + url);
}
        });//All requests open in the local webview

webView.setWebChromeClient(new WebChromeClient());//Support for special JavaScript
//        webView.loadUrl("http://www.17173.com");

webView.addJavascriptInterface(new MyJS(this), "android");

//Load Local Pages
webView.loadUrl("file:///android_asset/login.html");

Posted by narch31 on Sun, 02 Jun 2019 09:37:10 -0700