Introduction to the Basic Use of WebView
Introduction to Catalogue
0. Directory structure diagram for WebView
1. Advantages of using WebView
2. The easiest way to use WebView
3. Common methods of WebView
* 3.1 Back and Forward and Refresh of WebView
* 3.2 Status of WebView
* 3.3 Clear Cached Data
4. Introduction to Common Classes of WebView
* 4.1 WebSettings class
* 4.2 WebViewClient class
* 4.3 WebChromeClient class
5. Notes for WebView
* 5.1 Dynamic Creation of WebView Using Context as Global Context
* 5.2 When Activity is destroyed, destroy WebView
1. Advantages of using WebView
* It can display and render web pages directly and display web pages directly. * webview can be laid out directly with html files (on the network or in local assets) * Interactive calls with JavaScript
2. The easiest way to use WebView
* Layout
<WebView
android:id="@+id/wv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
//Note adding permissions:
<uses-permission android:name="android.permission.INTERNET"/>
- The simplest use in activity
webview = (WebView) findViewById(R.id.webView1);
webview.loadUrl("http://www.baidu.com/"); //Loading web resources
webView.loadUrl("file:///android_asset/example.html"); //Loading local resources
//At this time, we found a problem. After starting the application, we automatically opened the built-in browser of the system. To solve this problem, we need to set up WebViewClient for webview and rewrite the method:
webview.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
//When the return value is true, control to open WebView and call system browser or third-party browser for false
return true;
}
//You can also rewrite other methods
});
3. Common methods of WebView
- 3.1 Back and Forward and Refresh of WebView
* WebView may not be used much in advance, but the ability to rollback is quite useful. When loading a web page, we click on several layers of links, click the return key, and then suddenly quit the application or destroy the current component. We believe that this interaction is not what the user needs, because it is possible that the user just wants to go back to the next level of the page.
* Introduction and use of methods
//Determine if there is a fallback and return true
webView.canGoBack();
//Return to the previous level
webView.goBack();
//Judging whether you can move forward, you can return to true
webView.canGoForward();
//Get to the next level
webView.goForward();
//Refresh
webView.reload();
//Rewrite Physical Keys - Return Logic is important
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK) {
if(wv.canGoBack()) {
wv.goBack();//Return to the previous page
return true;
}
}
return super.onKeyDown(keyCode, event);
}
- 3.2 Status of WebView
//Activate WebView to be active and can normally execute web page responses
webView.onResume() ;
//When a page loses focus and is switched to the background invisible state, the onPause // notifies the kernel to suspend all actions, such as DOM parsing, plugin execution, JavaScript execution, through onPause action.
webView.onPause();
//When an application (with webview) is switched back to the background, this method is not only for the current webview, but also for the whole application. It pauses the layout, parsing, and JavaScript timer of all webviews. Reduce CPU power consumption.
webView.pauseTimers()
//Restore pauseTimers status
webView.resumeTimers();
//Destroy Webview // When Activity is turned off, if the music or video of Webview is still playing. You must destroy Webview // but note that when WebView calls destory, WebView is still bound to Activity // because the context object // of the activity is passed in when a custom WebView is built, so you need to remove WebView from the parent container first, and then destroy webview:
rootLayout.removeView(webView);
webView.destroy();
- 3.3 Clear Cached Data
//Clear the cache left by web access
//Because the kernel cache is global, this approach is not only for webview, but also for the entire application.
Webview.clearCache(true);
//Clear the history of current webview access // Only webview accesses all records in the history except the current access record
Webview.clearHistory();
//This api only cleans up the form data that is automatically filled, and it does not cleanse up the data that WebView stores locally.
Webview.clearFormData();
4. Introduction to Common Classes of WebView
- 4.1 WebSettings class
- The main role is to configure and manage WebView
//Declare the WebSettings subclass
WebSettings webSettings = webView.getSettings();
//Note: This is important if you want to interact with Javascript in the pages you visit, then the webview must be set up to support Javascript.
webSettings.setJavaScriptEnabled(true);
//Support plug-ins
webSettings.setPluginsEnabled(true);
//Set up an adaptive screen for both
webSettings.setUseWideViewPort(true); //Adjust the image to the appropriate size for webview
webSettings.setLoadWithOverviewMode(true); // Scale to screen size
//Scaling operation
webSettings.setSupportZoom(true); //Support zooming, default to true. That's the premise below.
webSettings.setBuiltInZoomControls(true); //Set the built-in zoom control. If false, the WebView is not scalable
webSettings.setDisplayZoomControls(false); //Hide native zoom controls
//Other details
webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //Close caching in webview
webSettings.setAllowFileAccess(true); //Setting Accessible Files
webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //Support for opening new windows through JS
webSettings.setLoadsImagesAutomatically(true); //Support automatic loading of pictures
webSettings.setDefaultTextEncodingName("utf-8");//Setting the encoding format
- Setting up WebView Cache
- When loading an html page, WebView generates two folders, database and cache, in the / data/data / package name directory
- The requested URL record is saved in WebViewCache.db, and the content of the URL is saved in the WebViewCache folder.
- Whether caching is enabled:
//Prefer caching:
WebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//The caching mode is as follows:
//LOAD_CACHE_ONLY: Read only local cached data without using the network
//LOAD_DEFAULT:(default) Decides whether to retrieve data from the network based on cache-control.
//LOAD_NO_CACHE: Do not use caching, only get data from the network.
//LOAD_CACHE_ELSE_NETWORK uses the data in the cache whenever it is locally available, whether it expires or no-cache.
//No caching:
WebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setDomStorageEnabled(true); // Turn on the DOM storage API function
webSettings.setDatabaseEnabled(true); //Turn on the database storage API function
webSettings.setAppCacheEnabled(true);//Open Application Caches
String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
webSettings.setAppCachePath(cacheDirPath); //Setting up the Application Caches cache directory
4.2 WebViewClient class
- The main function is to handle various notification and request events.
- shouldOverrideUrlLoading() method
shouldOverrideUrlLoading()Method to open a web page without calling the system browser, but in this WebView In display
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
- onPageStarted()
Function: To start loading page calls, we can set up a loading page to tell the user that the program is waiting for the network response. webView.setWebViewClient(new WebViewClient(){ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // Setting the operation to start loading } });
- onPageFinished()
Function: Called at the end of page loading. We can close the loading bar and switch program actions. webView.setWebViewClient(new WebViewClient(){ @Override public void onPageFinished(WebView view, String url) { // Setting the end of loading operation } });
- onLoadResource()
Function: Page resources will be called when loading, and every resource (such as pictures) will be called once. webView.setWebViewClient(new WebViewClient(){ @Override public boolean onLoadResource(WebView view, String url) { // Setting up the operation of loading resources } });
- onReceivedError()
Function: When the server loading the page makes an error (e.g.404)Call.
App Inside use webview Control encounters such as404When this kind of error happens, it would be ugly to display the error prompt page in the browser, then our app You need to load a local error prompt page, which is webview How to load a local page
//Step 1: Write an HTML file (error_handle.html) to display the prompt page to the user when an error occurs.
//Step 2: Place the html file under the assets folder in the code root directory
//Step 3: Override the onRecievedError method of WebViewClient
//This method returns error codes and can classify errors according to their types.
webView.setWebViewClient(new WebViewClient(){
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
switch(errorCode){
case HttpStatus.SC_NOT_FOUND:
view.loadUrl("file:///android_assets/error_handle.html");
break;
}
}
});
- onReceivedSslError()
Role: Handling https requests By default, webView does not process https requests. The page displays blank space. The following settings are required: webView.setWebViewClient(new WebViewClient() { @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); // indicates waiting for certificate response // handler.cancel(); // means suspended connection by default // handler.handleMessage(null); // Can do other processing } });
- 4.3 WebChromeClient class
-
- The main function is to assist WebView in handling Javascript dialog boxes, website icons, website titles, and so on.
- onProgressChanged()
-
Function: Get the loading progress of the web page and display it webview.setWebChromeClient(new WebChromeClient(){ @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress < 100) { String progress = newProgress + "%"; progress.setText(progress); } } });
- onReceivedTitle()
Function: Get the title in the Web page Each page has a title. webview.setWebChromeClient(new WebChromeClient(){ @Override public void onReceivedTitle(WebView view, String title) { titleview.setText(title); } }
5. Notes for WebView
- 5.1 Dynamic Creation of WebView Using Context as Global Context
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
mWebView = new WebView(getApplicationContext());
mWebView.setLayoutParams(params);
mLayout.addView(mWebView);
- 5.2 When Activity is destroyed, destroy WebView
stay Activity Destruction( WebView )When it comes to time, let's do it first. WebView LoadnullContent, then remove WebView,Re-destruction WebView,Finally empty.
@Override
protected void onDestroy() {
if (mWebView != null) {
mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
mWebView.clearHistory();
((ViewGroup) mWebView.getParent()).removeView(mWebView);
mWebView.destroy();
mWebView = null;
}
super.onDestroy();
}
Follow-up:
I know: https://www.zhihu.com/people/yang-chong-69-24/pins/posts
Leading English: https://www.linkedin.com/in/chong-yang-049216146/
Brief Book: http://www.jianshu.com/u/b7b2c6ed9284
csdn: http://my.csdn.net/m0_37700275
Netease Blog: http://yangchong211.blog.163.com/
Sina blog: http://blog.sina.com.cn/786041010yc
github: https://github.com/yangchong211
Listen to Himalayas: http://www.ximalaya.com/zhubo/71989305/