Preface:
Today, a bug in the revision project about the use of WebView aroused my motivation to summarize WebView. Today, I have time to make a summary.
Use scenarios:
1. Adding permissions
<uses-permission 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
Loading local resources
webView.loadUrl("file:///android_asset/example.html");
Loading 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 data";
webView.loadData(data, "text/html", "utf-8");
Actual testing will find that loadData will lead to Chinese scrambling, so generally use the following code
String data = " Html data";
webView.loadDataWithBaseURL(null,data, "text/html", "utf-8",null);
4. Support JavaScript
For example, the project total js triggers a native function to close Activity
Setting up support for JavaScript
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);//Setting up support for javascript
webView.addJavascriptInterface(new JavaScriptInterface(), "xueleapp");
JavaScript Interface Interface Interface Definition
public class JavaScriptInterface {
@android.webkit.JavascriptInterface
public void doTrainFinish() {
finish();
}
}
5. Setting up WebViewClient mainly assists WebView in handling various notification and request events.
For example, to implement links in WebView to jump inside WebView
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
In addition, WebViewClient handles more address parsing and rendering of Web pages, such as
onLoadResource//Response when loading resources
onPageStart//Response when loading pages
onPageFinish//Response at the end of loading the page
onReceiveError//Response to load errors
onReceivedHttpAuthRequest//Authorization Request for Getting Return Information
6. Setting up WebChrome Client mainly assists WebView to process Javascript dialog boxes, website icons, website title, loading progress, etc.
For example, load progress to get title
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
//Page Loading Completed
} else {
//Page Loading
}
}
});
In addition to the above progress, there are
onCloseWindow//Close WebView
onCreateWindow() //Trigger to create a new window
onJsAlert //Trigger to pop up a dialog box
onJsPrompt //Trigger a prompt to pop up
onJsConfirm//Trigger pop-up confirmation prompt
onProgressChanged //Loading progress
onReceivedIcon //Get icon
onReceivedTitle//Get the title of the page
7.) Setting up Page Stack to Return
By default, webview stores past pages on a stack, so we sometimes need to implement a fallback to the previous directory.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (webView.canGoBack()) {
webView.goBack();//Return to the previous browse page
return true;
} else {
finish();//Close Activity
}
}
return super.onKeyDown(keyCode, event);
}
8.) WebView Cache Control
•LOAD_CACHE_ONLY: Instead of using the network, read only local cached data
•LOAD_DEFAULT: according to cache-control Decide whether to retrieve data from the network or not.
•LOAD_CACHE_NORMAL: API level 17Has been abandoned, from API level 11Start with the same effect LOAD_DEFAULT Pattern
•LOAD_NO_CACHE: Do not use caching, only get data from the network.
•LOAD_CACHE_ELSE_NETWORK,Whether it's expired or not, as long as it's locally available no-cache,All use the data in the cache.
WebSettings webSettings = webView.getSettings();
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
9.) WebView Screen Adaptation
WebSettings webSettings = webView.getSettings();
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
10. Other infrequent settings
WebSettings webSettings = webView.getSettings();
webSettings.setSupportZoom(true); //Support scaling
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //Support content repositioning
webSettings.supportMultipleWindows(); //Multiple windows
webSettings.setAllowFileAccess(true); //Setting Accessible Files
webSettings.setNeedInitialFocus(true); //Set up nodes for webview when requestFocus is invoked by webview
webSettings.setBuiltInZoomControls(true); //Setting support for zooming
webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //Support for opening new windows through JS
webSettings.setLoadsImagesAutomatically(true); //Support automatic loading of pictures
11.) Knowledge Extension WebView JSBridge
Although Google also provides a way for js and native functions to call each other, there are some security risks in Android version 4.2 or below by addjavascript Interface, and the @JavascriptInterface annotation is also needed in Android version 4.2 or above, otherwise it can not be invoked. For the above reasons, I recommend learning.
WebViewJSBridge is a good open source framework, address:
12. Hardware Acceleration
Turning on hardware acceleration and forcing GPU rendering really improves the fluency of app s, but in the process of using WebView flicker, it also leads to loading WebView black screen or white screen.
Solution: Turn off hardware acceleration
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
This is to speed up the shutdown of hardware in webview. After setting LAYER_TYPE_SOFTWARE, the current view will be saved in bitmap. In this way, you can't open multiple webviews, otherwise you will report out of memory.
You need to add the following code to the webview
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
invalidate();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}