Objective:
Modification of a project today on the use of a bug in WebView, inspired me to summarize the motives of WebView, today to make a summary.
Usage scenario: 1.) Add permissions
<android:name= "Android.permission.INTERNET"/>
2.) Layout file
< WebView Android:id = "@+id/webview" android:layout_width= "Match_parent" android:layout_height= " Match_parent "/>
3.) Data loading
Load Local Resources
Webview.loadurl ("file:///android_asset/example.html");
Load network resources
Webview.loadurl ("www.xxx.com/index.html");
Add Request header Information
map<string,string> map=New hashmap<string,string>();
Map.put ("User-agent", "Android"); Webview.loadurl ("www.xxx.com/index.html", map);
You can also load HTML fragments
String data = "Html" "text/html", "utf-8");
The actual test will find that loaddata can cause Chinese garbled, so the following code is commonly used
String data = "Html"; Webview.loaddatawithbaseurl (null, data, "text/html", "Utf-8",null) ;
4.) Support JavaScript
For example, project Total JS triggers a native function to close activity
Setting up JavaScript support
WebSettings websettings = webview.getsettings (); websettings.setjavascriptenabled (true); // The settings support JavaScript webview.addjavascriptinterface (new javascriptinterface (), "Xueleapp");
Javascriptinterface Interface Definition
Public class javascriptinterface { @android. webkit.javascriptinterface publicvoid Dotrainfinish () { finish (); } }
5.) Set Webviewclient Primary auxiliary WebView to handle various notifications, request events
For example, to implement the WebView link in the WebView internal jump
Webview.setwebviewclient (new webviewclient () { publicboolean Shouldoverrideurlloading (WebView view, String URL) { view.loadurl (URL); return true ; } });
In addition to webviewclient more address parsing and rendering of web pages, such as
onloadresource//Response when loading resources
onpagestart//response when loading a page
onpagefinish//response at the end of the load page
onreceiveerror//Response on Load Error
onreceivedhttpauthrequest//Get return Information authorization request
6.) Set Webchromeclient main auxiliary webview Processing JavaScript dialog box, website icon, website title, loading progress etc.
Like load progress get title
Webview.setwebchromeclient (new webchromeclient () { @Override publicvoid int newprogress) { if (newprogress = =) { // Web page loading complete Else { // page Load }}} );
In addition to the above detection progress, there are
onclosewindow//Close WebView
Oncreatewindow ()//trigger to create a new window
Onjsalert//Trigger Popup a dialog box
Onjsprompt//Trigger Popup a hint
onjsconfirm//Trigger Popup Confirmation prompt
Onprogresschanged//Load Progress
Onreceivedicon//Get page icon
onreceivedtitle//Get page title
7.) Set the page stack to return
WebView will default to the browsing of the past pages to the stack storage, so we sometimes need to implement fallback to the previous directory
@Override Public BooleanOnKeyDown (intKeyCode, KeyEvent event) { if(KeyCode = =keyevent.keycode_back) { if(Webview.cangoback ()) {webview.goback ();//go back to previous browse page return true; } Else{finish ();//Close Activity } } return Super. OnKeyDown (KeyCode, event); }
8.) WebView Cache Control
- Load_cache_only: Do not use the network, only read local cache data
- Load_default: Decide whether to fetch data from the network according to Cache-control.
- Deprecated in Load_cache_normal:api level 17, starting from API level 11 with Load_default mode
- Load_no_cache: Do not use caching, only get data from the network.
- Load_cache_else_network, the data in the cache is used whenever there is a local, regardless of whether it expires, or No-cache.
WebSettings websettings = webview.getsettings (); Websettings.setcachemode (Websettings.load_cache_else_network) ;
9.) WebView Screen Adaptive
WebSettings websettings = webview.getsettings (); Websettings.setusewideviewport (true); Websettings.setloadwithoverviewmode (true);
10.) Other infrequently used settings
WebSettings websettings =webview.getsettings (); Websettings.setsupportzoom (true);//Support ScalingWebsettings.setlayoutalgorithm (WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//support for content re-layoutWebsettings.supportmultiplewindows ();//Multi-WindowWebsettings.setallowfileaccess (true);//settings can access filesWebsettings.setneedinitialfocus (true);//set node for WebView when WebView calls RequestfocusWebsettings.setbuiltinzoomcontrols (true);//Setting Support ScalingWebsettings.setjavascriptcanopenwindowsautomatically (true);//support to open a new window via JSWebsettings.setloadsimagesautomatically (true);//supports automatic loading of pictures
11.) Knowledge Extension Webviewjsbridge
While Google also provides a way for JS and native functions to call each other, but through Addjavascriptinterface this way in Android 4.2 The following version of a certain security risk, in the Android More than 4.2 also need to add @javascriptinterface annotations, otherwise cannot be called. Based on the reasons above, suggest learning
Webviewjsbridge This relatively good open source framework, address: Https://github.com/firewolf-ljw/WebViewJSBridge
12.) Hardware acceleration
Turn on hardware acceleration to force GPU rendering, does give the app a smooth degree of promotion, but in the use of the process encountered WebView flashing, also cause loading webview black screen or white screen
Workaround: Turn off hardware acceleration
null);
This is the hardware acceleration shutdown in the webview. Setting Layer_type_software will convert the current view to bitmap save. This will not open multiple webview, otherwise it will be reported out of memory.
You need to add the following code to the WebView
protected void onmeasure (intint heightmeasurespec) { invalidate (); Super . Onmeasure (Widthmeasurespec, Heightmeasurespec); }
WebView Use summary of Android