Introduction
Many Android apps now have built-in interfaces that display web pages, and you'll find that the interface is usually rendered by a component called WebView that you can learn to extend for your app development.
1. Overview of WebView
As it literally means, it is used to display Web pages.The WebView control allows us to use PC-side Web pages directly in App, and the addJavascriptInterface method enables JavaScript and Java methods to call each other, reducing development costs.In short, WebView is a small built-in browser.
2. Common methods of WebView
1. Construction methods
Method Name | Parameter Description |
---|---|
WebView(Context context) | Pass-through context for accessing application resources |
WebView(Context context, AttributeSet attrs) | attrs: the set of attributes passed to the parent container |
WebView(Context context, AttributeSet attrs, int defStyle) | defStyle: id of style style resource |
2. Other Common Methods
Method Name | Parameter Description | Usage Description |
---|---|---|
void addJavascriptInterface(Object obj, String interfaceName) | obj: Custom Java object, instance variable name used when calling in interfaceName:js | Bind objects to Javascript, a method that can be accessed from JavaScript. |
boolean canGoBack()/canGoBackOrForward()/canGoForward() | Set whether to allow return to previous page, forward, etc. | |
boolean dispatchKeyEvent(KeyEvent event) | event object | Set up event delivery |
String getOriginalUrl() | Get the original Url | |
int getProgress() | Get the progress of the current page | |
WebSettings getSettings() | Gets a collection of WebView properties for configuring WebView | |
void loadData(String data, String mimeType, String encoding) | data: html code in string concatenation | Used to render html code as a string into the form of a web page |
void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl) | ||
void loadUrl(String url) | Render the url file or url web address as a web page | |
void setWebChromeClient(WebChromeClient client) | Set to open i using a local WebView instead of a system browser |
3. Application of WebView
1. Basic steps for using WebView
- First, you can construct a WebView, which can be declared directly in the xml layout by static construction, or created dynamically by java code.
<?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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<WebView android:id="@+id/id_table_webview" android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
mWebview = (WebView) findViewById(R.id.id_table_webview);//Get WebVIew
WebView webView = new WebView(context);
- Second, configure WebView in the Activity's life cycle method (typically onCreate) (mainly by calling getSetting() to get the property set and set it up, setting javascript support, fallback, whether to open with the system's own browser, and so on)
public class MyWebViewCient extends WebViewClient {
/**
* WebView Hyperlinks that respond to pages
* @param view
* @param url
* @return
*/
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
mWebview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);///A series of initialization settings
mWebview.getSettings().setAllowFileAccess(true);// Set Allow Access to File Data
mWebview.getSettings().setSupportZoom(true);//Support for enlarging web pages
mWebview.getSettings().setBuiltInZoomControls(true);//Supports Web Page Reduction
mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.addJavascriptInterface(new JSObject(), "employee");//The first object, the call name in the second js (we can see that this instance of the JSObject class is employee, which is used to make calls in javascript)
mWebview.setWebViewClient(new MyWebViewCient());//Set to open i without using the system browser.Open with Local WebView
- Then call loadUrl, loadData, loadDataWithBaseURL to load and display the corresponding page content
mWebView.loadUrl("http://www.google.com"); //Loading url addresses for the Internet
mWebView.loadUrl("file:///android_asset/xxx.html"); //Load and display html stored under assets file
mWebView.loadUrl("file:///mnt/sdcard/web/xxx.html" );//Load html under sdcard
//Set a fallback to override the onKeyDown(int keyCoder,KeyEvent event) method of the Activity class
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebview.canGoBack()) {
mWebview.goBack(); //Return to the previous page of the WebView
return true;
}
return false;
}
- Next, if you jump to another page with a WebView point link, in order for WebView to support fallback, you need to override the onKeyDown() method of the Activity class; otherwise, click the system fallback clipping key and the browser will call finish() to end itself instead of going back to the previous page.
5. Finally, you need to add permissions to the AndroidManifest.xml file - uses-permission android:name="android.permission.INTERNET", otherwise you will get a Web page not available error.
package com.xiaoi.app.smartbot.view.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.xiaoi.app.smartbot.R;
/**
* auther: Crazy.Mo
* Date: 2017/4/5
* Time:15:08
* Des:
*/
public class WebViewActivity extends BaseActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
init();
}
private void init(){
webView= (WebView) findViewById(R.id.id_webv);
initWebView();
}
private void initWebView(){
if(getIntent()!=null) {
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);///A series of initialization settings
webView.getSettings().setAllowFileAccess(true);// Set Allow Access to File Data
webView.getSettings().setSupportZoom(true);//Support for enlarging web pages
webView.getSettings().setBuiltInZoomControls(true);//Supports Web Page Reduction
webView.getSettings().setJavaScriptEnabled(true);
///webView.addJavascriptInterface (new JSObject (),'employee'); //front object, call name in subsequent js (we can see this instance of JSObject class is employee, which is used to call in javascript)
webView.loadUrl(getIntent().getStringExtra("url"));
webView.setWebViewClient(new MyWebViewCient());//Set to open i without using the system browser.Open with Local WebView
}
}
public static void openWebViewActivity(@NonNull Context context,@NonNull int requestCode,@NonNull String url){
WebViewActivity activity=new WebViewActivity();
Intent intent=new Intent(context,WebViewActivity.class);
intent.putExtra("url", url);
context.startActivity(intent);
///activity.startActivityForResult(intent,requestCode);
}
//Set a fallback to override the onKeyDown(int keyCoder,KeyEvent event) method of the Activity class
// @Override
// public boolean onKeyDown(int keyCode, KeyEvent event) {
// if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
// webView.goBack(); //Return to the previous page of WebView
// return true;
// }
// return false;
// }
private static class MyWebViewCient extends WebViewClient {
/**
* WebView Hyperlinks that respond to pages
* @param view
* @param url
* @return
*/
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
4. Notes when using WebView
1. When loading js, css, and html resources from local assets, writing html files to reference these resources requires introducing absolute paths corresponding to assets
2. When loading and displaying web pages using loadData(data) method, the data contains the following four special characters:'#','%','\', if any, can be replaced with%23,%25,%27,%3f. Resolving Chinese scrambling code can transfer encoding - utf-8 to solve otherwise it may cause errors.
%: Page error will be reported, the page is full of garbage. #: Will invalidate your goBack, but canGoBack is available.This results in a situation where the return button takes effect but cannot be returned. \: When converting, errors will occur because it will use \ as an escape character and will not work if two levels of escaping are used
//Good Transcoding Scheme at Present
final String digits = "0123456789ABCDEF";
public String encode(String s){
StringBuilder buf = new StringBuilder(s.length() + 16);
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
|| (ch >= '0' && ch <= '9') || ".-*_".indexOf(ch) > -1) { //$NON-NLS-1$
buf.append(ch);
} else {
byte[] bytes = new String(new char[] { ch }).getBytes();
for (int j = 0; j < bytes.length; j++) {
buf.append('%');
buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
buf.append(digits.charAt(bytes[j] & 0xf));
}
}
}
return buf.toString();
}
mWebView.loadData(this.encode(html), "text/html", "utf-8");
It is worth noting that when I replace special characters and use loadData, if a large number of special characters and a large number of stytle s (which use a lot of% signs) have a big impact on the speed, the more data there is on the page, the slower it will run.
3. When loading pages with special characters, consider using the loadDataWithBaseURL method
4. There is no problem loading static Web pages. When loading remote (WIFI) dynamic pages, you need to be aware that there may be problems loading pictures (because the relative path given in the Web page is not a complete HTPP path, so sometimes you have to handle it yourself, otherwise the pictures will not load properly)
To be continued...