preface
-
At present, Hybrid apps are built into many apps, such as many e-commerce platforms such as Taobao, JINGdong, Juhuasuan.com, etc., as shown below
image -
So how does this work? In fact, this is an Android component called WebView implementation
-
Today, I’m going to present a comprehensive overview of the common uses of WebView.
directory
1. Introduction
WebView is a webKit-based control that presents web pages.
Android Webview has different kernel versions of WebKit in earlier and later versions, and uses Chrome directly after 4.4.
2. The role
- Display and render Web pages
- Layout directly using HTML files (on the Web or in local assets)
- Can be interactively called with JavaScript
WebView control is powerful, in addition to having general View properties and Settings, but also on THE URL request, page loading, rendering, page interaction for powerful processing.
3. Introduction to usage
In general, Webview can be used alone, in conjunction with its utility classes, so next, I’ll introduce:
- Common methods of the Webview class itself
- Webview’s most commonly used utility classes: WebSettings, WebViewClient, WebChromeClient
- Interaction between Android and Js
3.1 Common methods of Webview class
3.1.1 loading url
There are three loading modes based on resources
// Mode 1\. Load a page: webview.loadurl ("http://www.google.com/"); // Method 2: load the HTML page in the APK package webview.loadurl ("file:///android_asset/test.html"); // Method 3: Load the phone's local HTML page webview. loadUrl("content://com.android.htmlfileprovider/sdcard/test.html"); Webview. loadData(String data, String mimeType, String encoding) // Need to intercept the content of the presentation // cannot appear in the content '# ', '%', '\', '? If %23, %25, %27, %3f are used to replace these four characters, otherwise an exception will occur// Parameter 2: type of display content // Parameter 3: bytecodeCopy the code
3.1.1 WebView status
// Activate WebView to active state, can normally execute the web response webView.onresume (); // Use the onPause action to tell the kernel to pause all actions, such as DOM parsing, plugin execution, and JavaScript execution. WebView. OnPause (); This method does not only deal with the current webview, but with the whole application's webView. It pauses layout, parsing, and javascriptTimer on all webViews. Reduce CPU power consumption. Webview.pausetimers () // Restore the pauseTimers state webview.resumetimers (); // If the Webview music or video is still playing while the Activity is closed. You must destroy the Webview. When a webView calls deStory, the WebView is still attached to the Activity. This is because the Activity context was passed in when the custom WebView was built. rootLayout.removeView(webView); webView.destroy();Copy the code
3.1.2 About forward/Backward pages
Webview.cangoback (); webView.goback (); webView.cangoback (); Webview.gobackorforward (intsteps) webView.gobackorForward (intsteps) webView.gobackorForward (intsteps) webView.gobackorForward (intsteps)Copy the code
Common usage: The Back key controls the web page Back
- Problem: If you click the system’s “Back” key while browsing a web page, the entire Browser calls Finish () to terminate itself without doing anything
- The goal: after clicking back, the page rewind instead of launching the browser
- Solution: Process and consume the Back event in the current Activity
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
Copy the code
3.1.3 Clearing Cached Data
Since the kernel cache is global, this method applies not only to the WebView but to the entire application. Webview.clearCache(true); Webview.clearhistory (); webView.clearHistory (); // This API only clears the auto-populated form data, not the data stored locally by the WebView.Copy the code
3.2 Common Tools
3.2.1 WebSettings class
- Function: Configures and manages the WebView
- Configuration Steps & Common methods:
Configuration Step 1: Add access to the network (Androidmanifest.xml)
That’s the premise! That’s the premise! That’s the premise!
<uses-permission android:name="android.permission.INTERNET"/>
Copy the code
Configuration Step 2: Generate a WebView component (there are two ways)
WebView = new WebView(this) // Method 2: Add the WebView control to the Activity layout file: WebView webview = (WebView) findViewById(R.id.webView1);Copy the code
Step 3: Configure – Subclass WebSettings (common method)
// Declare WebSettings subclass WebSettings WebSettings = webView.getSettings(); / / if the access to the page with Javascript interaction, the webview must set support Javascript webSettings. SetJavaScriptEnabled (true); // If the loading HTML has JS performing animation and other operations, will cause a waste of resources (CPU, battery) // in onStop and onResume respectivelysetJavaScriptEnabled() is set tofalse 和 trueCan / / support plug-in webSettings. SetPluginsEnabled (true); / / set the adaptive screen, both share webSettings. SetUseWideViewPort (true); / / adjust the images to fit the size of the webview webSettings. SetLoadWithOverviewMode (true); / / resized to the size of the screen / / zooming webSettings. SetSupportZoom (true); // Support scaling, default istrue. That's the premise of the following one. webSettings.setBuiltInZoomControls(true); // Set the built-in zoom control. iffalse, then the WebView cannot zoom webSettings. SetDisplayZoomControls (false); SetCacheMode (websettings.load_cache_else_network); / / close webview cache webSettings. SetAllowFileAccess (true); / / set can access the file webSettings. SetJavaScriptCanOpenWindowsAutomatically (true); / / support by JS webSettings. Open a new window setLoadsImagesAutomatically (true); / / support automatic loading pictures webSettings. SetDefaultTextEncodingName ("utf-8"); // Set the encoding formatCopy the code
Common usage: Set up WebView cache
- When loading HTML pages, WebView generates database and cache folders in the /data/data/ package name directory
- The requested URL record is stored in webViewCache.db, and the URL content is stored in the WebViewCache folder
- Whether to enable caching:
// Cache is preferred: webView.getsettings ().setcachemode (websettings.load_cache_else_network); // Cache modes are as follows: //LOAD_CACHE_ONLY: reads only local cache data without using the network. //LOAD_DEFAULT: decides whether to fetch data from the network according to cache-control. //LOAD_NO_CACHE: no cache is used, only data is obtained from the network. //LOAD_CACHE_ELSE_NETWORK: data in the cache is used whenever it is locally available, regardless of expiration or no-cache. // Do not use cache: webView.getSettings ().setCachemode (websettings.load_no_cache);Copy the code
- Combined use (offline loading)
if(NetStatusUtil.isConnected(getApplicationContext())) { webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); Cache-control determines whether to fetch data from the network. }else{ webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); / / not net, is obtained from the local, the off-line load} webSettings. SetDomStorageEnabled (true); / / open the DOM storage API function webSettings. SetDatabaseEnabled (true); / / open the database storage API function webSettings. SetAppCacheEnabled (true); String cacheDirPath = getFilesDir().getabsolutePath () + APP_CACAHE_DIRNAME; // Enable Application Caches. webSettings.setAppCachePath(cacheDirPath); // Sets the Application Caches cache directoryCopy the code
Note: each Application. Just call a WebSettings setAppCachePath (), WebSettings. SetAppCacheMaxSize ()
3.2.2 WebViewClient class
- Function: Handles notification & request events
- Common methods:
ShouldOverrideUrlLoading ()
- Function: open the web page does not call the system browser, but in the WebView display; All the loading on a web page goes through this method, and there’s a lot we can do with this function.
Webview Webview = (Webview) findViewById(R.i.wiebView1); // Step 2\. Select loading mode // Mode 1\. Load a page: webview.loadurl ("http://www.google.com/"); // Method 2: load the HTML page in the APK package webview.loadurl ("file:///android_asset/test.html"); // Method 3: Load the phone's local HTML page webview. loadUrl("content://com.android.htmlfileprovider/sdcard/test.html"); ShouldOverrideUrlLoading () method to display webView.setWebViewClient(new) in this WebView instead of calling the system browser when opening a web pageWebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true; }});Copy the code
Common method 2: onPageStarted()
- We can set a loading page to tell the user that the program is waiting for a network response.
webView.setWebViewClient(new WebViewClient(){@override public void onPageStarted(WebView view, String url, Bitmap favicon) {// Set the loading action}});Copy the code
Common method 3: onPageFinished()
- Function: Called at the end of page loading. We can turn off the loading bar to switch program actions.
webView.setWebViewClient(new WebViewClient(){@Override public void onPageFinished(WebView view, String URL){// Set the loading end operation}});Copy the code
Common method 4: onLoadResource()
- Function: called when page resources are loaded, once for each resource (such as images) loaded.
webView.setWebViewClient(new WebViewClient(){@override public Boolean onLoadResource(WebView view, String URL){});Copy the code
Common method 5: onReceivedError ()
- Function: Called when there is an error (such as 404) on the server that loaded the page.
App inside the use of webview control when encountered such as 404 error, if also display browser inside the error page will appear very ugly, then this time our App needs to load a local error page, that is, how to load a local page webView
// Step 1: Write an HTML file (error_handle.html), which is used to display the prompt page to the user in case of an error. // Step 2: Put the HTML file in the assets folder in the root directory of the code. // Step 3: Webview.setwebviewclient (new) this method returns an error code that can be classified according to the type of errorWebViewClient(){
@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; }}});Copy the code
Common method 6: onReceivedSslError()
- Function: Processes HTTPS requests
By default, the webView does not process HTTPS requests and the page is blank. You need to set the following parameters:
webView.setWebViewClient(new WebViewClient() { @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); // wait for the certificate response // handler.cancel(); // Handler. HandleMessage (null); }}); 5.1 By default, HTTPS and HTTP are disabledif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
Copy the code
3.2.3 WebChromeClient class
- Function: Assist WebView to handle Javascript dialog box, website icon, website title and so on.
- Common uses:
Common method 1: onProgressChanged ()
- Function: get page loading progress and display
webview.setWebChromeClient(new WebChromeClient(){
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress < 100) {
String progress = newProgress + "%";
progress.setText(progress);
} else{}});Copy the code
Common method 2: onReceivedTitle ()
- Gets the title of a Web page
Each page of the page has a title, such as www.baidu.com the title of the page is “Baidu, you know”, so how to know the current webview is loading the page title and set it?
webview.setWebChromeClient(new WebChromeClient(){@Override public void onReceivedTitle(WebView view, String title) {titleView.settext (title); }Copy the code
Common method 3: onJsAlert ()
- What it Does: Supports javascript warning boxes
Generally, it is Toast on Android, and you can wrap the text by adding \n to it
webview.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("JsAlert")
.setMessage(message)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setCancelable(false)
.show();
return true;
}
Copy the code
Common method 4: onJsConfirm ()
- What it does: Supports javascript confirmation boxes
webview.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("JsConfirm")
.setMessage(message)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
})
.setCancelable(false) .show(); // Returns a Boolean value: confirm or cancel when clicked //trueClick ok;falseClick cancel;return true;
}
Copy the code
Common method 5: onJsPrompt ()
- What it does: Supports javascript input boxes
Click OK to return the value in the input box, and click Cancel to return NULL.
webview.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
final EditText et = new EditText(MainActivity.this);
et.setText(defaultValue);
new AlertDialog.Builder(MainActivity.this)
.setTitle(message)
.setView(et)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm(et.getText().toString());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
})
.setCancelable(false)
.show();
return true;
}
Copy the code
3.3 WebView and JavaScript interaction
Take a look at my article: The most comprehensive & detailed summary of Android WebView and JS interactions
3.4 Precautions: How to avoid WebView memory leaks?
3.4.1 Instead of defining webViews in XML, they are created in the Activity when needed, and the Context uses getApplicationgContext()
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
mWebView = new WebView(getApplicationContext());
mWebView.setLayoutParams(params);
mLayout.addView(mWebView);
Copy the code
3.4.2 When the Activity destroys (WebView), first let the WebView load null content, then remove the WebView, then destroy the WebView, and 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();
}
Copy the code
Example 4.
- Objective: To display “www.baidu.com”, get its title, prompt loading start & end, and get loading progress
- Concrete implementation:
Step 1: Add network access permission
That’s the premise! That’s the premise! That’s the premise!
<uses-permission android:name="android.permission.INTERNET"/>
Copy the code
Step 2: Main layout
<? xml version="1.0" encoding="utf-8"? > <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.carson_ho.webview_demo.MainActivity"> <! --> <TextView Android :id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/ > <! <TextView Android :id="@+id/text_beginLoading"
android:layout_below="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/ > <! <TextView Android :layout_below="@+id/text_beginLoading"
android:id="@+id/text_Loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/ > <! <TextView Android :layout_below="@+id/text_Loading"
android:id="@+id/text_endLoading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""/ > <! <WebView Android :id="@+id/webView1"
android:layout_below="@+id/text_endLoading"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="10dp" />
</RelativeLayout>
Copy the code
Step 3: Use the appropriate subclasses and their methods based on the functionality you need to implement (the comments are clear)
package com.example.carson_ho.webview_demo;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
WebView mWebview;
WebSettings mWebSettings;
TextView beginLoading,endLoading,loading,mtitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebview = (WebView) findViewById(R.id.webView1);
beginLoading = (TextView) findViewById(R.id.text_beginLoading);
endLoading = (TextView) findViewById(R.id.text_endLoading);
loading = (TextView) findViewById(R.id.text_Loading);
mtitle = (TextView) findViewById(R.id.title);
mWebSettings = mWebview.getSettings();
mWebview.loadUrl("http://www.baidu.com/"); / / browser Settings without system open, direct display in the current Webview mWebview. SetWebViewClient (newWebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true; }}); / / set the WebChromeClient mWebview. SetWebChromeClient (newWebChromeClient@override public void onReceivedTitle(WebView view, String title) {system.out.println () {Override public void onReceivedTitle(WebView view, String title) {system.out.println ("Here's the title."); mtitle.setText(title); @override public void onProgressChanged(WebView view, int newProgress) {if (newProgress < 100) {
String progress = newProgress + "%";
loading.setText(progress);
} else if (newProgress == 100) {
String progress = newProgress + "%"; loading.setText(progress); }}}); / / set the WebViewClient class mWebview. SetWebViewClient (newWebViewClient@override public void onPageStarted(WebView view, String url, Bitmap favicon) {system.out.println () {Override public void onPageStarted(WebView view, String url, Bitmap favicon) {system.out.println ("It's loading.");
beginLoading.setText("It's loading."); @override public void onPageFinished(WebView view, String URL) {endLoad.settext ("Finished loading."); }}); } @override public Boolean onKeyDown(int keyCode, KeyEvent event) {if (keyCode == KeyEvent.KEYCODE_BACK && mWebview.canGoBack()) {
mWebview.goBack();
return true;
}
returnsuper.onKeyDown(keyCode, event); } // destroy webview@override protected voidonDestroy() {
if(mWebview ! = null) { mWebview.loadDataWithBaseURL(null,""."text/html"."utf-8", null); mWebview.clearHistory(); ((ViewGroup) mWebview.getParent()).removeView(mWebview); mWebview.destroy(); mWebview = null; } super.onDestroy(); }}Copy the code
The Demo address
Source code: Carson_Ho Github-WebviewDemo
5. To summarize
- This article gives a comprehensive introduction
Webview
, summarized as follows
Author: Carson_Ho links: www.jianshu.com/p/3c94ae673…